Safe zero-copy operations in C#

https://news.ycombinator.com/rss Hits: 16
Summary

C# is a versatile language. You can write mobile apps, desktop apps, games, websites, services and APIs with it. You can write it like Java with all the abstractions and AbstractionFactoryClassProviders. But differently from Java, you can write low-level and unsafe code too. When I say low-level, I mean without the GC, with raw pointers. Low-level code is usually required for performance or interoperability with C libraries or the operating system. The reason low-level code helps with performance is that it can be used to eliminate runtime checks on memory accesses.Array element accesses are bounds-checked in C# for safety. But, that means that there's performance impact unless the compiler can eliminate a bounds-checking operation. The bounds-checking elimination logic needs to ensure that the array index was already bounds-checked before, or can be assured to be inside bounds during the compile-time. For example, take this simple function:int sum(int[] array) { int sum = 0; for (int i = 0; i < array.Length; i++) { sum += array[i]; } return sum; }That's an ideal situation for bounds-checking elimination because the index variable i is created with known boundaries, and it depends on the array's length. The index variable's lifetime is shorter than the array's lifetime and it's guaranteed to be contained valid values throughout the function. The native code produced for sum has no bounds-checking:L0000 xor eax, eax L0002 xor edx, edx L0004 mov r8d, [rcx+8] ; read length L0008 test r8d, r8d ; is empty? L000b jle short L001c ; skip the loop L000d mov r10d, edx L0010 add eax, [rcx+r10*4+0x10] ; sum += array[i]; L0015 inc edx ; i++ L0017 cmp r8d, edx ; compare length with i L001a jg short L000d ; loop if still greater L001c ret But, what if the function signature was slightly different?int sum(int[] array, int startIndex, int endIndex) { int sum = 0; for (int i = startIndex; i <= endIndex; i++) { sum += array[i]; } return sum; }Now, the C# compiler doesn't have a way to...

First seen: 2025-09-30 01:35

Last seen: 2025-09-30 16:38