Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference in performance for calling .length on an array versus saving a size variable?

I am creating a simulation program, and I want the code to be very optimized. Right now I have an array that gets cycled through a lot and in the various for loops I use

 for(int i = 0; i<array.length; i++){
       //do stuff with the array
 }

I was wondering if it would be faster if I saved a variable in the class to specify this array length, and used that instead. Or if it matters at all.

like image 923
wfbarksdale Avatar asked Dec 10 '11 16:12

wfbarksdale


People also ask

Does .length work on arrays?

The length variable is applicable to an array but not for string objects whereas the length() method is applicable for string objects but not for arrays.

Why do we use .length in array?

We can use the length of an array to fetch the lowest value present in an array object.

What happen if you assign value more than size in array?

If you try to access the array position (index) greater than its size, the program gets compiled successfully but, at the time of execution it generates an ArrayIndexOutOfBoundsException exception.

What does .length return for an array?

The length property sets or returns the number of elements in an array.


1 Answers

Accessing the length attribute on an array is as fast as it gets.

You'll see people recommending that you save a data structure size before entering the loop because it means a method all for each and every iteration.

But this is the kind of micro-optimization that seldom matters. Don't worry much about this kind of thing until you have data that tells you it's the reason for a performance issue.

You should be spending more time thinking about the algorithms you're embedding in that loop, possible parallelism, etc. That'll be far more meaningful in your quest for an optimized solution.

like image 141
duffymo Avatar answered Nov 19 '22 01:11

duffymo