Saturday, March 8, 2014

String.Concat vs String.Format Performance

Time for another micro-optimization!

When building strings it is almost always easiest to write and maintain a typical format statement. However, what is the cost of that over just concatenating strings? When building strings for cache keys (which I know are going to get called a lot) I try to use String.Concat instead of String.Format. Let's look at why!

Below is a table showing a comparison the performance difference between String.Concat and String.Format. The Y axis is the number of arguments being concatenated. The X axis is the number of milliseconds it takes to complete 100,000 runs.

Number
of Args
String.Concat
Milliseconds
String.Format
Milliseconds
Concat
Percent Faster
2 4ms 10ms 150%
3 3ms 13ms 333%
4 4ms 16ms 300%
5 12ms 21ms 75%
6 14ms 24ms 71%
7 16ms 28ms 75%
8 18ms 31ms 72%

Here is an example of the code that was used to test this:

// This averaged 4 milliseconds
var stopwatchConcat2 = Stopwatch.StartNew();
for (var i = 0; i < 100000; i++)
    String.Concat("1", "2");
stopwatchConcat2.Stop();
 
// This averaged 10 milliseconds
var stopwatchFormat2 = Stopwatch.StartNew();
for (var i = 0; i < 100000; i++)
    String.Format("1{0}", "2");
stopwatchFormat2.Stop();

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics