.NET runtime is a managed execution runtime which (among other things) provides garbage collection. .NET garbage collector (GC)
not only manages the allocation and release of memory, but also transparently moves the objects around the “managed heap”, blocking
the rest of your code while doing it.
It also compacts (defragments) the memory by moving longer lived objects together, and even “promoting” them into different parts of the heap, called generations, to avoid checking their status too often.
There is a bunch of memory being copied all the time without your program even realizing it. Since garbage collection is an operation that can happen at any time during the execution of your program, any pointer-related
(“unsafe”) operations must be done within a small scope, by telling the runtime to “pin” the objects using the fixed
keyword. This prevents the GC from moving them, but only for a while.
Using pointers and unsafe
code in C# is not only less safe, but also not very idiomatic for managed languages in general. If coming from a C background, you may feel like at home with these constructs, but C# has a completely different philosophy: your job as a C# programmer should be to write reliable, readable and maintenable code, and only then think about squeezing a couple of CPU cycles for performance reasons. You can use pointers from time to time in small functions, doing some very specific, time-critical code. But even then it is your duty to profile before making such optimizations. Even the most experienced programmers often fail at predicting bottlenecks before profiling.
Finally, regarding your actual code:
-
I don’t see why you think this:
int*[] pp = new int*[] {&aaa, &bbb, &ccc};
would be any more performant than this:
int[] pp = new int[] {aaa, bbb, ccc};
On a 32-bit machine, an
int
and a pointer are of the same size. On a 64-bit machine, a pointer is even bigger. -
Consider replacing these plain
int
s with aclass
of your own which will provide some context and additional functionality/data to each of these values. Create a new question describing the actual problem you are trying to solve (you can also use Code Review for such questions) and you will benefit from much better suggestions.
solved C# – How to Bypass Error cs0212 Cheaply for Programmers and Computers?