c++ - Inside Function: Copy value from array or repeated access by index -


i have question regarding efficiency/performance when accessing arrays inside functions. let's have function loops through array 5,000 elements. inside function, access array x multiple times @ index x[k].
performance perspective, advantageous assign value @ index k temporary variable in loop, such tmpval = x[k]? in other words, can increase speed of execution avoiding accessing array @ same position on , on again?

thank much!

let me prefix saying you're trying achieve micro-optimization @ best, , should focus on making code easy follow, rather trying squeeze out performance here.

realistically, there no difference between:

  1. accessing element in array index, and
  2. accessing copy on stack.

due smart use of processor's on-die caches, first time access element of array copied cache , there extremely fast access.

if did create temporary copy, you're copying object new location, more expensive (probably) accessing object inside array.


Comments