java - Why is getting a value from a variable preferred than getting it from an array? -


consider below program:

int []array = {10, 20, 30, 40, 50}; int x = array[0]; for(int = 0; < array.length; i++) {  system.out.println(x * array[i]);  system.out.println(array[0] * array[i]); } 

when array declared, stored in memory reside together.

array:     [0]    [1]    [2]    [3]   [4] value:     10     20     30     40    50 location:  100   102     104    106   108 

now when x assigned value first element of array(10).

x stored value in memory value 10.

variable :  x value :     10 location :  120 

now when call loop,

the first print statement refer value @ location 120 , have value 10.

the second print statement refer location 100 , has value 10.

when both statements have memory location every time, why first statement more optimal?

edit in same program if x used multiple times.

int []array = {10, 20, 30, 40, 50}; int x = array[0]; for(int = 0; < array.length; i++) {  system.out.println(x * array[i] + (x + 1) * array[i] - ( x + 2));  system.out.println(array[0] * array[i] + (array[0] + 1) * array[i] - (array[0] + 2)); } 

here x used many times. people prefer using x calling array[0] everytime.

both have looked though.

when accessing array[i], processor has memory address array , add i address variable requested.

when accessing x processor can variable directly x.

in java, primitives stored on stack array pointer on heap whereas x stored on stack. applies if x primitive though. if array contains objects (and x pointer object), both stored on heap.

so main difference when accessing array[i] you'll accessing location-of-array-plus-i, when accessing x you'll accessing location-of-x. it's worth noting array[0] (or other fixed index) can optimised single instruction.

now, should worry this? no, absolutely not. there unlikely measurable performance difference between these 2 ways , if there is extremely unlikely performance difference affect - application doing lot more time-consuming work accessing variables in memory. compiler optimise reduce number of memory lookups required , processor caches play role too.

the real reason preferable write like:

int x = array[0] int y = array[1] int result = x + y + x * y + x * (x - y) 

is lot more readable than:

int result = array[0] + array[1] + array[0] * array[1] + array[0] * (array[0] - array[1]) 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -