Performance-wise, is it better to access an array element ‘directly’ multiple times, or assign its value to a variable and use that variable? Assuming I’ll be referencing the value several times in the following code.
The reasoning behind this question is that, accessing an array element presumably involves some computing cost each time it is done, without requiring extra space. On the other hand, storing the value in a variable eliminates this access-cost, but takes up extra space.
// use a variable to store the value
Temp = ArrayOfValues(0)
If Temp > 100 Or Temp < 50 Then
Dim Blah = Temp
...
// reference the array element 'directly'
If ArrayOfValues(0) > 100 Or ArrayOfValues(0) < 50 Then
Dim Blah = ArrayOfValues(0)
...
I know this is a trivial example, but assuming we’re talking about a larger scale in actual use (where the value will be referenced many times) at what point is the tradeoff between space and computing time worth considering (if at all)?
The overhead in memory consumption is very limited because for reference types it’s just a pointer (couple of bytes) and most value types also require just a few bytes.
Arrays are very efficient structures in most languages. Getting to an index doesn’t involve any lookup but just some math (each array slot takes 4 bytes so the 11th slot is at offset 40). Then there is probably a bit of overhead for bounds checking. Allocating the memory for a new local var and freeing it requires a bit of cpu cycles as well. So in the end it also depends how many array lookups you eliminate by copying to a local var.
Fact is that you really need exceptionally crappy hardware or have really big loops for this to be really important and if it is run a decent test on it. I personally choose often for the seperate variable as I find that it makes the code more readible.
Your example is odd btw since you do 2 array lookups before you create the local var 🙂
This makes more sense (elimination 2 more lookups)