Same plans, markedly different performance!

We all know the importance of looking at execution plans when doing performance optimization. However, just because the plan looks good doesn’t necessarily indicate the best outcome. It’s always important to consider the user-experience, and this might mean investigating a different method of obtaining the equivalent output. This post looks at a great example of that.

A Simple PlanIn a previous post, I talked about how to store a number with leading zeros. This morning I came across an interesting function that could be used in SQL Server 2012 and higher to obtain the same result without using string concatenation. FORMATMESSAGE (MSDN page here) provides a mechanism to format a variable using zeros padding, exactly like our requirement!

The FORMATMESSAGE function follows the “C” convention for variable substitution used by the printf function. That is, a portion of the string starting with a space followed by a % symbol, then a “type” indicator such as “i” or “s” will be replaced by values passed into the function. See the RAISERROR page on MSDN for details about how the substitution works.

I thought, surely this function, being designed to provide the desired functionality, would be more efficient than the string concatenation method. I also added code to test the FORMAT function. Let’s take a look…

For this test, I’ve simplified the table from the prior post – this is the test-bed code:

The plans for the three SELECT statements at the end are:

Plan #1



Cool! The plans are the same. Looks good so far. Next I used SET STATISTICS IO, TIME ON; to display I/O and duration statistics for each operation. The results of which are:

| #MyTestConcat        | 3          | 8053           |   342          |   262              |
| #MyTestFormatMessage | 3          | 8053           |  6552          |  3323              |
| #MyTestFormat        | 3          | 8053           | 27846          | 16783              |

Oh. It appears the concatenating and truncating (#MyTestConcat) method is far-and-away the quickest method.

The takeaway for this is don’t just look at the execution plans when evaluating code for performance. Although execution plans are invaluable, they don’t tell you anything about how much time it actually takes to run.

If you found this post useful, please
consider donating a small amount
to help keep the lights on and site running.