In C#, I have an array of structs and I need to assign values to each. What is the most efficient way to do this? I could assign each field, indexing the array for each field:
array[i].x = 1;
array[i].y = 1;
I could construct a new struct on the stack and copy it to the array:
array[i] = new Vector2(1, 2);
Is there another way? I could call a method and pass the struct by ref, but I'd guess the method call overhead would not be worth it.
In case the struct size matters, the structs in question have 2-4 fields of type float or byte.
In some cases I need to assign the same values to multiple array entries, eg:
Vector2 value = new Vector2(1, 2);
array[i] = value;
array[i + 1] = value;
array[i + 2] = value;
array[i + 3] = value;
Does this change which approach is more efficient?
I understand this is quite low level, but I'm doing it millions of times and I'm curious.
Edit: I slapped together a benchmark:
this.array = new Vector2[100];
Vector2[] array = this.array;
for (int i = 0; i < 1000; i++){
long startTime, endTime;
startTime = DateTime.Now.Ticks;
for (int x = 0; x < 100000000; x++) {
array[0] = new Vector2(1,2);
array[1] = new Vector2(3,4);
array[2] = new Vector2(5,6);
array[3] = new Vector2(7,8);
array[4] = new Vector2(9,0);
array[5] = new Vector2(1,2);
array[6] = new Vector2(3,4);
array[7] = new Vector2(5,6);
array[8] = new Vector2(7,8);
array[9] = new Vector2(9,0);
}
endTime = DateTime.Now.Ticks;
double ns = ((double)(endTime - startTime)) / ((double)loopCount);
Debug.Log(ns.ToString("F"));
}
This reported ~0.77ns and another version which indexed and assigned the struct fields gave ~0.24ns, FWIW. It appears the array index is cheap compared to the struct stack allocation and copy. Might be interesting to see the performance on a mobile device.
Edit2: Dan Bryant's answer below is why I didn't write a benchmark to begin with, too easy to get wrong.