Skip to content

Instantly share code, notes, and snippets.

@remzmike
Created May 13, 2017 14:06
Show Gist options
  • Save remzmike/e64b0f84bb0e5da10591bee9db14f3f8 to your computer and use it in GitHub Desktop.
Save remzmike/e64b0f84bb0e5da10591bee9db14f3f8 to your computer and use it in GitHub Desktop.
IndexOf vs Dictionary
public void Old(string s) {
var matchCount = 0;
for (var i=0;i<4000;i++) {
var key = String.Format(",{0},", i);
if (s.IndexOf(key) >= 0) {
matchCount++;
}
}
Console.WriteLine(String.Format("s matches: {0}", matchCount));
}
public void New(Dictionary<string, bool> d) {
var matchCount = 0;
for (var i=0;i<4000;i++) {
var key = String.Format(",{0},", i);
if (d.Keys.Contains(key)) {
matchCount++;
}
}
Console.WriteLine(String.Format("d matches: {0}", matchCount));
}
void Main()
{
Stopwatch watch;
var sb = new StringBuilder();
var d = new Dictionary<string, bool>();
for (var i=0;i<2000;i++) {
var key = String.Format(",{0},", i);
sb.Append(key);
d[key] = true;
}
string s = sb.ToString();
Console.WriteLine("s length: " + s.Length);
watch = new Stopwatch();
watch.Start();
Old(s);
watch.Stop();
Console.WriteLine(String.Format("{0}ms", watch.ElapsedMilliseconds));
watch = new Stopwatch();
watch.Start();
New(d);
watch.Stop();
Console.WriteLine(String.Format("{0}ms", watch.ElapsedMilliseconds));
}
/*
s length: 10890
s matches: 2000
74ms
d matches: 2000
1ms
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment