Search code examples
c#multithreadingperformancecpu-cache

Is there a performance disadvantage to not copying reference types to each thread in C#?


I am working on implementing threading to my C# program. Each thread requires access to the same array, but does not need to write to it, only read data. Should this array be deep copied for each thread?

The reason I think this might be important (from my very limited knowledge of threading) is so that threads on different CPU cores can store copies of the array in their own cache instead of constantly requesting data from a single core's cache where the array is stored, but perhaps the compiler or something else will optimise away this inefficiency?

Any insight would be much appreciated.


Solution

  • Since you haven't specified the hardware architecture you are running on I'm going to assume it is either and Intel or AMD x64 processor. In which case I recommend trusting the processor to correctly optimize this situation. By creating multiple copies that the processor that the compiler can't know are duplicate copies you will force the processor to use more memory and spread the available cache space over more memory lessening it's effectiveness.