// quiz10.cs // this program is offered as is with no warranty implied and confers no rights.
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace Quiz10 { class Program { [ThreadStatic] private static Dictionary myItems = new Dictionary(); private static LocalDataStoreSlot slotStatic; [ThreadStatic] private static Data myData = new Data(); class Data { public int i = 0; } static void Main(string[] args) { slotStatic = Thread.AllocateNamedDataSlot("foo"); Thread.SetData(slotStatic, new Data()); myItems["foo"] = new Data(); const int count = 10000000; // get any jitting out of the way Test1(); Test2(); Test3(); Test4(); int i = 0; System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch(); s.Start(); for (i = 0; i < count; i++) Test1(); s.Stop(); Console.WriteLine("Test1: Named Slot {0:n0}ms", s.ElapsedMilliseconds); s.Reset(); s.Start(); for (i = 0; i < count; i++) Test2(); s.Stop(); Console.WriteLine("Test2: Numbered Slot {0:n0}ms", s.ElapsedMilliseconds); s.Reset(); s.Start(); for (i = 0; i < count; i++) Test3(); s.Stop(); Console.WriteLine("Test3: Thread-local dictionary {0:n0}ms", s.ElapsedMilliseconds); s.Reset(); s.Start(); for (i = 0; i < count; i++) Test4(); s.Stop(); Console.WriteLine("Test4: Thread-local direct {0:n0}ms", s.ElapsedMilliseconds); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static void Test1() { LocalDataStoreSlot slot = Thread.GetNamedDataSlot("foo"); Data d = (Data)Thread.GetData(slot); d.i++; } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static void Test2() { Data d = (Data)Thread.GetData(slotStatic); d.i++; } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static void Test3() { Data d = myItems["foo"]; d.i++; } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static void Test4() { myData.i++; } } }