I recently read this post about poor performance of fields marked ThreadStatic - they're apparently 60x slower than normal field access. Does .NET 4's ThreadLocal< T > perform any better?
Are there any alternatives that offer high performance thread-specific storage?
Bear in mind that that was in 2008 - I believe that .NET 4 is a lot faster for ThreadStatic
fields than .NET 3.5 was. I can't remember for sure, but you could run tests if you want.
That said, I'm not really convinced by the test description - because it's unrealistic. Do you really need to repeatedly read a thread-local field in a loop? Isn't it more likely that you'll read it once, and then once a bit later on in a different bit of code?
Ultimately, the real question is whether either or both of these approaches performs well enough for your particular requirement. I prefer ThreadLocal<T>
to ThreadStatic
not for performance reasons, but because it allows for appropriate initialization - see my article on randomness for an example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With