Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance wise, is it better to call the length of a given array every time or store the length in a variable and call that variable every time?

I call on the length of a given array a lot and I was wondering if it is better to keep calling it numerous times (50+ times currently, but it keeps growing) or is it better to just store the length in an integer and use that integer every time.

If I am unclear in what I am saying, consider the following:

I have a String array:

String[] str = new String[500]; //The length is actually dynamic, not static

Of course, I put some values into it, but I call on the length of the string all the time throughout my application:

int a = str.length;
int b = str.length;
int c = str.length;
int d = str.length;
int e = str.length;

and so on...so is it better to do this: (performance wise, don't care about memory as much)

int length = str.length;
    int a = length;
    int b = length;
    int c = length;
    int d = length;
    int e = length;

Thanks.

like image 456
Gaff Avatar asked Jul 08 '11 15:07

Gaff


People also ask

Why do we need array length?

array. length: length is a final variable applicable for arrays. With the help of the length variable, we can obtain the size of the array.

How expensive is array length in Javascript?

Iterating over a thousand items, using array. length will only cost you an extra 2 ms. In other words: beware premature optimization.

How do you use array length in a for loop?

As already mentioned, you can iterate through an array using the length attribute. The loop for this will iterate through all the elements one by one till (length-1) the element is reached (since arrays start from 0). Using this loop you can search if a specific value is present in the array or not.


1 Answers

There is no difference. You don't call a method when accessing the length of the array. You just read an internal field. Even if you called a method, the difference would be negligible with current JVMs.

like image 82
JB Nizet Avatar answered Oct 13 '22 02:10

JB Nizet