Skip to content

Instantly share code, notes, and snippets.

@yallie
Created February 22, 2013 06:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yallie/5011260 to your computer and use it in GitHub Desktop.
Save yallie/5011260 to your computer and use it in GitHub Desktop.
HashSet<char>.Contains(c) versus string.Contains(c)
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