1

Could someone explain the runtime and downsides of repeatedly accessing an array and if it is better to store the String value from the array as a temporary string. For example if I have an array of strings is it better to do

int paramLength = params.length;
for (int i=1; i<paramLength; i++){

or

for (int i=1; i<params.length; i++){

I would think the first option is better in the above case. The trade off being accessing the length inside the array object once and storing it vs. repeatedly accessing the length.

Also, once I'm inside the for loop and I need to use the string from the array multiple times is it better to store the String in the array as a local variable or to keep accessing the array and why is it better?

for (int i=1; i<paramLength; i++){
System.out.println(params[i]);

or

for (int i=1; i<paramLength; i++){
String temp = params[i];
System.out.println(temp);

or

for (String s: params) 
System.out.println(s);

Sorry if this is repeated but I couldn't find more knowledge on the downsides of accessing these values inside the array vs storing it locally.

javakid1993
  • 237
  • 2
  • 7
  • 19
  • 1
    I think you will find that there is no measurable performance difference and this is a question of style. Use whichever version is easiest to read and [**Write Dumb Code**](http://www.oracle.com/technetwork/articles/javase/devinsight-1-139780.html). – Elliott Frisch Oct 23 '14 at 17:50
  • @ElliottFrisch thank you, I think the referencing to the same location in memory is what I was forgetting and thus the only benefit would be simpler and more readable code. – javakid1993 Oct 23 '14 at 18:30

1 Answers1

0

Ultimately the array indexing and the String object are just pointing to data some place in memory, you are just referring to some place in memory each time so there is absolutely no difference in performance from that aspect.

This line just gives you another pointer to the same place in memory. When you reference either on of them you are getting the same data from the same location in memory.

String temp = params[i];

If we're talking about large sets of data (lots of strings), it is better to use an array than a bunch of String objects. This is because the String objects can be sparsely scattered throughout memory, ie on different cache and page frames. So using an array will give you continuity in the location of data giving you better cache and page/frame performance.