Skip to content

Instantly share code, notes, and snippets.

@justinvp
Created May 24, 2015 12:37
Show Gist options
  • Save justinvp/16d41b1734d7c152b4a8 to your computer and use it in GitHub Desktop.
Save justinvp/16d41b1734d7c152b4a8 to your computer and use it in GitHub Desktop.
String.Split microbenchmark
using System;
using System.Diagnostics;
public class Program
{
public static void Main()
{
const string test = "This is a sentence to use for testing.";
string[] separator = new string[] { " " };
var sw = new Stopwatch();
const int ITERS = 10000000;
while (true)
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Console.Write("A: ");
sw.Restart();
for (int i = 0; i < ITERS; i++)
{
// Operation A
test.SplitOld(separator, 1, StringSplitOptions.None);
}
var elapsedA = sw.Elapsed;
Console.WriteLine(elapsedA);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Console.Write("B: ");
sw.Restart();
for (int i = 0; i < ITERS; i++)
{
// Operation B
test.Split(separator, 1, StringSplitOptions.None);
}
var elapsedB = sw.Elapsed;
Console.WriteLine(elapsedB);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Console.WriteLine("A/B : {0}",
elapsedA.TotalMilliseconds /
elapsedB.TotalMilliseconds);
Console.WriteLine("B/A : {0}",
elapsedB.TotalMilliseconds /
elapsedA.TotalMilliseconds);
Console.WriteLine("(A-B)/A : {0}",
Math.Abs((elapsedA.TotalMilliseconds -
elapsedB.TotalMilliseconds) /
elapsedA.TotalMilliseconds));
Console.WriteLine("(B-A)/B : {0}",
Math.Abs((elapsedB.TotalMilliseconds -
elapsedA.TotalMilliseconds) /
elapsedB.TotalMilliseconds));
Console.WriteLine();
Console.ReadLine();
}
}
}
A: 00:00:01.6835160
B: 00:00:00.1366061
A/B : 12.3238713351746
B/A : 0.0811433333570931
(A-B)/A : 0.918856666642907
(B-A)/B : 11.3238713351746
A: 00:00:01.7130745
B: 00:00:00.1377855
A/B : 12.4329083974729
B/A : 0.0804317033497376
(A-B)/A : 0.919568296650263
(B-A)/B : 11.4329083974729
A: 00:00:01.6833079
B: 00:00:00.1387093
A/B : 12.1355085780117
B/A : 0.0824028093731397
(A-B)/A : 0.91759719062686
(B-A)/B : 11.1355085780117
A: 00:00:01.6823955
B: 00:00:00.1397315
A/B : 12.0402021018883
B/A : 0.0830550842533756
(A-B)/A : 0.916944915746624
(B-A)/B : 11.0402021018883
A: 00:00:01.6638048
B: 00:00:00.1403704
A/B : 11.852960453201
B/A : 0.0843671084492604
(A-B)/A : 0.91563289155074
(B-A)/B : 10.852960453201
A: 00:00:01.6723702
B: 00:00:00.1425899
A/B : 11.7285319647465
B/A : 0.0852621626479592
(A-B)/A : 0.914737837352041
(B-A)/B : 10.7285319647465
A: 00:00:01.6890087
B: 00:00:00.1366335
A/B : 12.3616001932176
B/A : 0.0808956756705871
(A-B)/A : 0.919104324329413
(B-A)/B : 11.3616001932176
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment