Skip to content

Instantly share code, notes, and snippets.

@mirasrael
Created February 11, 2019 10:05
Show Gist options
  • Save mirasrael/6b7e4566f76080b5f65440218e5593c8 to your computer and use it in GitHub Desktop.
Save mirasrael/6b7e4566f76080b5f65440218e5593c8 to your computer and use it in GitHub Desktop.
dict comparison
public static void Main (string[] args)
{
var iterations = 1000;
var size = 100000;
for (var i = 0; i < size; i++)
{
concurrent.Add(i.ToString(), i);
simple.Add(i.ToString(), i);
threadSafe.Add(i.ToString(), i);
}
var sw = Stopwatch.StartNew();
var max = 0;
for (var it = 0; it < iterations; it++)
{
Parallel.For(0, size, i =>
{
concurrent.TryGetValue(i.ToString(), out var element);
if (element > max)
max = element;
});
}
sw.Stop();
Console.WriteLine($"concurrent: {sw.Elapsed}");
sw = Stopwatch.StartNew();
max = 0;
for (var it = 0; it < iterations; it++)
{
Parallel.For(0, size, i =>
{
threadSafe.TryGetValue(i.ToString(), out var element);
if (element > max)
max = element;
});
}
sw.Stop();
Console.WriteLine($"thread-safe: {sw.Elapsed}");
sw = Stopwatch.StartNew();
var rw = new ReaderWriterLockSlim();
max = 0;
for (var it = 0; it < iterations; it++)
{
Parallel.For(0, size, i =>
{
rw.EnterReadLock();
try
{
simple.TryGetValue(i.ToString(), out var element);
if (element > max)
max = element;
}
finally
{
rw.ExitReadLock();
}
});
}
sw.Stop();
Console.WriteLine($"rw + simple: {sw.Elapsed}");
sw = Stopwatch.StartNew();
max = 0;
for (var it = 0; it < iterations; it++)
{
Parallel.For(0, size, i =>
{
lock (simple)
{
simple.TryGetValue(i.ToString(), out var element);
if (element > max)
max = element;
}
});
}
sw.Stop();
Console.WriteLine($"lock + simple: {sw.Elapsed}");
}
private static IDictionary<string, int> concurrent = new ConcurrentDictionary<string, int>();
private static IDictionary<string, int> threadSafe = new ThreadSafeDictionary<string, int>();
private static IDictionary<string, int> simple = new ConcurrentDictionary<string, int>();
@mirasrael
Copy link
Author

concurrent: 00:00:02.7575280
thread-safe: 00:00:05.3959692
rw + simple: 00:00:24.2981597
lock + simple: 00:00:27.4054182

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment