DEV Community

Saurabh Ranjan
Saurabh Ranjan

Posted on

Optimized way to iterate over the length in js loop?

Which code is faster and optimized. Or it doesn't matter if we are not looping over larger data.


 for (var i = 0; i < msg.stackTrace.length; ++i) {
   ...
 }

or

var stackTraceLength = msg.stackTrace.length;
 for (var i = 0; i < stackTraceLength; ++i) {
  ....
 }

Top comments (6)

Collapse
 
nerdlyist profile image
Coury Ryan Richards

The next level question "is how can I figure out what is more optimal". Learning to profile your code is a huge benefit. Also, with questions like this you need to know what you are optimizing for memory, cpu, network speed, etc. If the ... is n API calls you have other concerns then if it is say file writes.

You should look into forEach, map or reduce. All of which solve specific cases for array iteration.

In the end this would be considered a micro optimization. Just get the coding done and refactor. Variable set vs function calls like size should not matter too much.

Collapse
 
warriorofsunlight profile image
WarriorOfSunlight

On the topic of array iteration and array functions, I would highly recommend that you take a minute to really look through the array prototype methods: developer.mozilla.org/en-US/docs/W...

There are several you may never end up using but having high level knowledge of the common ones (namely, forEach, map, filter, and reduce) is always useful. As Ryan has stated, the optimizations you're looking to make will save you a minimal amount of fetch/processing time at best.

Collapse
 
dexygen profile image
George Jempty

The length variable does not need to be outside the loop, this is how I've been doing it for years:

for (var i = 0, n = msg.stackTrace.length; i < n; i++) {
Collapse
 
atwright147 profile image
Andy Wright

As far as I know there is no difference there. The length property isn't calculated when you access it is calculated when you push, pop etc

Collapse
 
inrsaurabh profile image
Saurabh Ranjan

You mean internally it's been tracked that when stackTrace is updated ?

Collapse
 
atwright147 profile image
Andy Wright

Sorry, I don't understand your comment