Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do static classes cause performance issues on multi-core systems?

the other day a colleague of mine stated that using static classes can cause performance issues on multi-core systems, because the static instance cannot be shared between the processor caches. Is that right? Are there some benchmarks around proofing this statement? This statement was made in the context of .Net development (with C#) related discussion, but it sounds to me like a language and environment independent problem.

Thx for your comments.

like image 935
Prensen Avatar asked Mar 13 '26 06:03

Prensen


2 Answers

I would push your colleague for data or at least references.

The thing is, if you've got shared data, you've got shared data. Whether that's exposed through static classes, a singleton, whatever, isn't terribly important. If you don't need the shared data in the first place, I expect you wouldn't have a static class anyway.

Besides all of this, in any given application there's likely to be a much bigger bottleneck than processor caches for shared data in static classes.

As ever, write the most sensible, readable, maintainable code first - then work out if you have a performance bottleneck and act accordingly.

like image 123
Jon Skeet Avatar answered Mar 16 '26 00:03

Jon Skeet


"[a] static instance cannot be shared between the processor caches. Is that right?"

That statement doesn't make much sense to me. The point of each processor's dedicated cache is that it contains a private copy of a small patch of memory, so that if the processor is doing some algorithm that only needs to access that particular memory region then it doesn't have to go to keep going back to access the external memory. If we're talking about the static fields inside a static class, the memory for those fields may all fit into a contiguous chunk of memory that will in turn fit into a single processor's (or core's) dedicated cache. But they each have their own cached copy - it's not "shared". That's the point of caches.

If an algorithm's working set is bigger than a cache then it will defeat that cache. Meaning that as the algorithm runs, it repeatedly causes the processor to pull data from external memory, because all the necessary pieces won't fit in the cache at once. But this is a general problem that doesn't apply specifically to static classes.

I wonder if your colleague was actually talking not about performance but about the need to apply correct locking if multiple threads are reading/writing the same data?

like image 44
Daniel Earwicker Avatar answered Mar 15 '26 23:03

Daniel Earwicker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!