Created
February 22, 2013 06:35
-
-
Save yallie/5011260 to your computer and use it in GitHub Desktop.
HashSet<char>.Contains(c) versus string.Contains(c)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Linq; | |
struct Program | |
{ | |
static void Main() | |
{ | |
const int iterations = 10000000; | |
string smallString = "<>*"; | |
string largeString = "@<>d+-0123456789abcdefghijklm<#"; | |
string testChars = "sglkjhw!%6*&^)()vxz.,mnbc/.qeRHD4rloi2405,nas@%%^*$%*dsfskh32XCBW5643g"; | |
var smallSet = new HashSet<char>(smallString); | |
var largeSet = new HashSet<char>(largeString); | |
Benchmark("String, small", iterations, x => smallString.Contains(testChars[x % testChars.Length])); | |
Benchmark("String, large", iterations, x => largeString.Contains(testChars[x % testChars.Length])); | |
Benchmark("HashSet<char>, small", iterations, x => smallSet.Contains(testChars[x % testChars.Length])); | |
Benchmark("HashSet<char>, large", iterations, x => largeSet.Contains(testChars[x % testChars.Length])); | |
} | |
static void Benchmark(string title, int iterations, Action<int> code) | |
{ | |
var sw = Stopwatch.StartNew(); | |
for (var i = 0; i < iterations; i++) | |
{ | |
code(i); | |
} | |
sw.Stop(); | |
Console.WriteLine("{2} Time elapsed: {0}, single iteration: {1} ms", sw.Elapsed, sw.Elapsed.TotalMilliseconds / iterations, title); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment