Accessing an array element directly and assigning it to a variable

Effectively, is it better to access the element of the array "directly" several times or assign its value to a variable and use this variable? Assuming I will refer to the value several times in the following code.

The reasons for this question are that accessing an array element seems to imply some computational cost each time this is done, without additional space. On the other hand, storing the value in a variable eliminates this access cost, but takes up additional 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 are talking about a larger scale in real use (where the value will be referenced many times), at what point is there a trade-off between space and computational time, which is worth considering (if at all)?

+5
source share
2 answers

The overhead of consuming memory is very limited, because for reference types it's just a pointer (a couple of bytes) and most value types also require just a few bytes.

. , ( 4 , 11- - 40). , , . var . , , , var.

, , , . , , .

- , 2 var:) ( 2 )

Dim blah = ArrayOfValues(0)
if blah > 100 or blah < 50 then
...
+2

, , . C ++ .

"" ; C ++ , , . .

int a = myarray[19];
int b = myarray[19] * 5;
int c = myarray[19] / 2;
int d = myarray[19] + 3;

, myarray int [], - "", operator[](), , , ( , , ).

"" , , , ( ). .

int a = myarray[19];
NiftyFunction();
int b = myarray[19] * 8;

, , myarray [19] .

, , , "" . , :

int a = myarray[19];
NiftyFunction();
assert(myarray[19] == a);
int b = a * 8;

, , - .

+2

All Articles