0

Hi I came across the following code as a response to a stackoverflow questions. Following was the answer which has got no direct connection to the question but it seems to improve the efficiency the of code.

for (int i = 0; i < nodeList.getLength(); i++)

change to

for (int i = 0, len = nodeList.getLength(); i < len; i++)

to be more efficient. The second way may be the best as it tends to use a flatter, predictable memory model.

I read about flat memory model but I couldn't get the point here. i.e., in what way does it makes the code more efficient. Can somebody explain me.

Ref: https://stackoverflow.com/a/12736268/3320657

Community
  • 1
  • 1

2 Answers2

0

nodeList.getLength() isn't called every time the program loops, instead it is called once, stored in the integer len, and then compares i to len instead of running nodeList.getLength().

0

Flat memory model or linear memory model refers to a memory addressing paradigm in which "memory appears to the program as a single contiguous address space." The CPU can directly (and linearly) address all of the available memory locations without having to resort to any sort of memory segmentation or paging schemes.

Keeping this in mind, the computer declares memory one line at a time. When declaring the variable within the line itself it causes less of a strain on seeking the value.

for (int i = 0, len = nodeList.getLength(); i < len; i++)

is more efficient than;

len = nodelist.getLength();
for (int i = 0, i < len; i++)
Caleb Bach
  • 162
  • 11