Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadStatic vs. ThreadLocal<T> Performance: speedups or alternatives?

Tags:

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?

like image 391
Mark Avatar asked Sep 30 '10 08:09

Mark


1 Answers

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.

like image 107
Jon Skeet Avatar answered Oct 05 '22 21:10

Jon Skeet