Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are .NET singletons made less performant as the application runs for longer?

I have been reading about garbage collection and memory management in .NET. I would like to ask the following to check my understanding:

Suppose I have a singleton that is created at the start of the application and is in generation 0 of the GC. Then imagine I have another class that references this singleton and is also near to it in memory (as it is also in generation 0). Is it reasonable to infer that they could be in the same cache line?

As the application runs, the GC promotes the object through to generation 1, and eventually generation 2. Any new objects created could now be quite far away from the singleton in memory. Am I right in assuming access between the new objects and the singleton could potentially be slower as they cannot be in the same cache line?

Does the GC make any attempt to keep objects that access each other frequently closer together in memory?

I am not looking to attempt to optimise code or second guess the garbage collector, I realise this is a contrived example. I am merely interested in the theory behind how the GC uses memory and how CPU caching works.

like image 722
Dave S Avatar asked Dec 09 '13 21:12

Dave S


1 Answers

Is it reasonable to infer that they could be in the same cache line?

This is possible, but it's fairly unlikely unless both objects happen to be quite small and allocated right after each other. I would not assume that they would lie on the same cache line, however, as this isn't something that you could control or enforce in practice.

As the application runs, the GC promotes the object through to generation 1, and eventually generation 2. Any new objects created could now be quite far away from the singleton in memory. Am I right in assuming access between the new objects and the singleton could potentially be slower as they cannot be in the same cache line?

There would be no difference, unless the two objects happened to be on the same exact cache line at the start. Once they're on different cache lines, the "distance" between them won't matter anymore.

Does the GC make any attempt to keep objects that access each other frequently closer together in memory?

No. Objects aren't reorganized and moved at runtime based on their access patterns. Objects are only moved due to compaction that occurs when there is free space due to previous collections.

Tracking usage and reference patterns would very complex, and likely reduce the overall performance.

like image 185
Reed Copsey Avatar answered Oct 14 '22 17:10

Reed Copsey