I’ve been reading a book assigned for class and it mentions that array access takes O(1) time. I realize that this is very fast (maybe as fast as possible), but if you have a loop that has to refer to this a few times, is there any advantage to assigning a temporary variable to have the value looked up in the array? Or would using the temporary variable still be O(1) to use as well?
I’m assuming this question is language independent. Also I realize that even if the answer is yes that the advantage is tiny, I’m just curious.
If I understand, you’re asking if
is any better than:
I wouldn’t worry about it:
If the code in the body of your loop is going to access the same array entry, say
ar[i]multiple times, any halfway decent compiler (at a nonzero optimization level) will keep that value in a register for quick re-use. In other words, the compiler will probably generate the exact same assembly given the either of the above code samples.Note that either of these is still O(1) (accessing one thing one time). Don’t confuse big-O notation of algorithms with instruction-level optimizations.
Edit
I just compiled a sample program with two functions, containing the above two samples, and at
-O2gcc 4.7.2 generated the exact same machine code; byte-for-byte.