C# List<T> of class instances and CPU cache performance

Gryff David 21 Reputation points
2022-09-03T18:01:46.153+00:00

If I do this:

List<MyClass> MyClassList = new List<MyClass>(100);  

Does that allocate me a contiguous block of memory for the object values? Classes are a reference type and from what I've read, the references in a List<T> are all stored in a contiguous block of memory. But what about the values that those references are pointing to? The references are basically just like C++ pointers, right? So they must be pointing to values in memory somewhere, right?

So then if I access an instance in that list and the CPU fetches it out of memory and it pulls a cache line with it, will that cache line contain the relevant object values that might be accessed next? Or will it just pull a cache line full of pointers to the next objects? And if it does cache a bunch of pointers, does it have to do another full 100 cycle access time to the RAM when it's asked to access the next thing in the List?

Are we not getting the benefit of modern CPU cache speeds to blaze through a List in C#?

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-09-03T18:20:09.43+00:00

    Does that allocate me a contiguous block of memory for the object values?

    In my opinion, it allocates a block of memory for references, and all of references are null. The values (objects) are not allocated yet and are not assigned to list elements. The public sources shows the 'new T[capacity]' statement, which allocates an array of nulls. The caching will be applied to this array of references.

    I think that 'new List<MyClass>' is similar to 'new std::vector<MyClass*>'.

    In case of 'List<MyStructure>' or 'List<int>', for example, it will allocate a block of values.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.