Created
March 2, 2017 15:22
-
-
Save zsoi/b858d85b63e1e477982a11728eaf0f0f to your computer and use it in GitHub Desktop.
Hack to avoid creating garbage by allocating very small arrays in C# - emulating an array with a struct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Hack to avoid creating lots of garbage by creating long[] arr = new long[2]; | |
// There may be ways to implement this in a better way | |
// But all of them coming to my mind involve unsafe code | |
// Quickly breaks down when trying to emulate larger arrays | |
// -> then using switch() to select the right values | |
// -> Some compilers will optimize the switch() as a binary search, but still - Unsafe implementation can be O(1)! | |
struct ulong2 | |
{ | |
ulong l0; | |
ulong l1; | |
public ulong this[ulong n] | |
{ | |
get | |
{ | |
return (n == 0) ? l0 : l1; | |
} | |
set | |
{ | |
if (n == 0) | |
{ | |
l0 = value; | |
} | |
else | |
{ | |
l1 = value; | |
} | |
} | |
} | |
} | |
static class Sample | |
{ | |
static void WithArray() | |
{ | |
ulong[] arr = new ulong[2]; | |
for(int n=0; n<1024; n++) | |
{ | |
arr[(n*3)%2]++; | |
} | |
} | |
static void WithoutArray() | |
{ | |
ulong2 arr = new ulong2(); | |
for(int n=0; n<1024; n++) | |
{ | |
arr[(n*3)%2]++; | |
} | |
} | |
public static void Main() | |
{ | |
// many bytes garbage | |
for(int n=0; n<1000; n++) | |
{ | |
WithArray(); | |
} | |
// Zero garbage | |
for(int n=0; n<1000; n++) | |
{ | |
WithoutArray(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment