Monday, February 6, 2012

Windows Phone Local Database tip: Exploring multiple UPDATEs and rowversion impact

According to the Local Database best practices, it is recommended to use a rowversion column in your local database table, if you are performing many updates. This blog post will examine the performance and changes to UPDATE handling that are caused by the presence of a rowversion column.

But first, how to add a rovversion column: If you are using code first, this simple column declaration will suffice:
private Binary _version;

If you are using database first, simply add a rowversion column like so:
ADD [Version] rowversion NOT NULL

Let us run the following test code which updates 100 rows with and without a rowversion column. I am using a prepopulated Chinook database, added as en embedded resource to the project. See this blog post for details on how to do this.

//New database from embedded resource
using (ChinookContext db = new ChinookContext(ChinookContext.ConnectionString))
if (db.DatabaseExists())


using (ChinookContext db = new ChinookContext(ChinookContext.ConnectionString))

db.LogDebug = true;

var arists = db.Artist.Take(100);

foreach (var artist in arists)
artist.Name = Guid.NewGuid().ToString();

System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();


catch (Exception ex)

Now lets us see what the SQL statements executed look like without a rowversion column on the table:

UPDATE [Artist]

SET [Name] = @p2

WHERE ([ArtistId] = @p0) AND ([Name] = @p1)

As you can see, a standard UPDATE statement is executed, including a WHERE clause referring to all columns in the table, in order to trap concurrency exceptions. The time to do 100 updates is about 320 ms.

Now let us add the rowversion column to the Artist table, recreate the DataContext so it contains the Version column, and run the same code.

Now the SQL statements look like so, indicating that the query processor is being bypassed:


--     ArtistId: [99]

--    )

-- EQUALITY CHECK [Version], [System.Byte[]] = [System.Byte[]]

-- [Name] <= [5ad7e0d2-925e-44f7-bcd7-c3bca32de745]

-- AUTOSYNC [Version] <= [System.Byte[]]

The time to do 100 updates is now about 110 ms, a significant improvement from 320 ms. So if you expect to do UPDATEs on your local Windows Phone database, add a rowversion column to your tables!


Christian Resma Helle said...

Excellent post Erik! I always knew it was faster but I didn't know it was that much faster!

A version column is automatically added when using the SQL Compact Code Generator to generate the data context. It's also wrapped in a #pragma warning disable/restore to avoid compiler warnings since the this column is never used in code

ErikEJ said...

Thanks, Christian! Great tip about the Code Generator, I will add a feature to enforce/inject rowversion columns on all tables in the Toolbox