Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop condition: array size - .length or constant?

Say, I've used a constant to allocate space for an array.

Later, when I access each position in the array using a for loop, should I address the test part using the .length value of the array or the constant value used during declaration?

In other words,

for (int i = 0; i < array.length; i++)

or

for (int i = 0; i < constantArraySize; i++)

?

Which one is better?

like image 956
MooMooCoding Avatar asked Sep 13 '25 18:09

MooMooCoding


1 Answers

Considering performance, none should be better than the other. Both should be in cache.

Considering readability, you should use array.length to make clear that you want to iterate over the array. So I would go for the first alternative.

like image 62
gexicide Avatar answered Sep 16 '25 09:09

gexicide