Groups | Blog | Home
all groups > dotnet performance > september 2006 >

dotnet performance : Sharing a static fields among several threads



Amir Shitrit
9/18/2006 3:34:01 AM
Is it true that sharing a static field among several threads hinders
performance?
Jon Shemitz
9/18/2006 7:33:51 AM
[quoted text, click to view]

No, not really. *Not* sharing a static field, by using the
[ThreadStatic] attribute, does hinder performance, because each access
requires a method call to get the address of this thread's copy.

Static fields can be more expensive under ASP (and with app domains in
general): any static field in a domain-neutral assembly (any
strong-named assembly, under ASP) is replicated in each new app
domain. My guess is that you've heard some mangled version of this.

--

..NET 2.0 for Delphi Programmers www.midnightbeach.com/.net
Amir Shitrit
9/18/2006 1:41:02 PM
Thank you all.
These answers actually provided me with more than I expected.

[quoted text, click to view]
Chris Mullins
9/18/2006 1:42:32 PM
[quoted text, click to view]

There's nothing intrinsically wrong with sharing a static field across any
number of threads. Performance will be just fine. Just make sure it's a
readonly field, and you're carefull about startup initialization.

Where you will run into troubles is if this field is read/write. Then you
have all the classic thread locking and synchronization issues to deal with.
You have a choice here of several things to use:

- Locking mechanisms (Montior / ReaderWriter / etc)
- Interlock Access
- Volatile Access to prevent optimizations

--
Chris Mullins, MCSD.Net, MCPD:Enterprise
http://www.coversant.net/blogs/cmullins

Vadym Stetsyak
9/18/2006 2:21:59 PM
SGVsbG8sIEFtaXIhDQoNCiBBUz4gSXMgaXQgdHJ1ZSB0aGF0IHNoYXJpbmcgYSBzdGF0aWMgZmll
bGQgYW1vbmcgc2V2ZXJhbCB0aHJlYWRzIGhpbmRlcnMgDQogQVM+IHBlcmZvcm1hbmNlPw0KIEFT
PiBJZiBzbywgd2h5IGlzIHRoYXQ/DQoNCklNTyBpdCBtYXkgaGluZGVyIHBlcmZvcm1hbmNlIGlm
IGFjY2VzcyB0byB0aGlzIHN0YXRpYyBmaWVsZCBpcyBzeW5jaHJvbml6ZWQgdmlhIGxvY2suLi4N
Cg0KLS0NClJlZ2FyZHMsIFZhZHltIFN0ZXRzeWFrDQp3d3c6IGh0dHA6Ly92YWRteXN0LmJsb2dz
cG90LmNvbQ==
Mrinal
9/18/2006 7:21:22 PM
I think static fields are already thread safe , so do you really need to enclose them into a synchronization block .

However , when i say thread safe , this is an internal implementation , so definitely going to have a performance impact , but
idea is their specific usage , how will you otherwise share a variable between threads for a common business logic .

[quoted text, click to view]
Jon Skeet [C# MVP]
9/18/2006 7:43:46 PM
[quoted text, click to view]

Absolutely, if they're potentially changing. See
http://www.pobox.com/~skeet/csharp/threads/volatility.shtml

[quoted text, click to view]

Threads can share objects too, so you can still use instance fields -
but you'll require some sort of synchronization, again.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
AddThis Social Bookmark Button