public
Created

Performance Showdown

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var cursors = new List<Cursor>();
cursors.Add(new Cursor
{
EscapedKey = "MyHub",
Id = 0
});
 
cursors.Add(new Cursor
{
EscapedKey = "MyHub2",
Id = 1
});
 
cursors.Add(new Cursor
{
EscapedKey = "MyHub.Group",
Id = 0
});
 
int iterations = 1000000;
 
var sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
MakeCursorJoin(cursors);
}
sw.Stop();
 
Console.WriteLine("Concat {0}", sw.Elapsed);
 
sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
MakeCursorStringBuilder(cursors);
}
sw.Stop();
Console.WriteLine("StringBuilder {0}", sw.Elapsed);
 
}
 
private static string MakeCursorJoin(IList<Cursor> cursors)
{
var serialized = new string[cursors.Count];
for (int i = 0; i < cursors.Count; i++)
{
serialized[i] = cursors[i].EscapedKey + ',' + cursors[i].Id;
}
 
return String.Join("|", serialized);
}
 
private static string MakeCursorStringBuilder(IList<Cursor> cursors)
{
var sb = new StringBuilder();
for (int i = 0; i < cursors.Count; i++)
{
if (i > 0)
{
sb.Append('|');
}
 
sb.Append(cursors[i].EscapedKey)
.Append(',')
.Append(cursors[i].Id);
}
 
return sb.ToString();
}
}
 
public class Cursor
{
public string EscapedKey { get; set; }
public ulong Id { get; set; }
}
}

Results

Concat: 00:00:00.8572315
StringBuilder: 00:00:00.7025375

Memory (I ran these by commenting out each and running the CLR profiler) for each method:
Concat:
Concat

StringBuilder:
StringBuilder

A quick test to share what I'm seeing (differently). Code was executed using LINQPad 4.42.05 beta (anyCPU) and LINQPad 4.42.01 (x86), respectively, and optimizations were turned on.

Results (x64)

Concat 00:00:00.5541643
StringBuilder 00:00:00.4194049

Results (x86)

Concat 00:00:00.4938912
StringBuilder 00:00:00.4087391

Test Configuration

  • OS Name: Microsoft Windows 7 Enterprise
  • Version: 6.1.7601 Service Pack 1 Build 7601
  • System Type: x64-based PC
  • Processor: Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz, 3401 Mhz, 4 Core(s), 8 Logical Processor(s)
  • Installed Physical Memory (RAM): 8.00 GB

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.