0

Is the length property on a string (or array) in JavaScript recalculated each time it's accessed? For example, if I access a string's length in a loop's condition statement, will it keep recalculating? I've seen it suggested that it is more efficient to save length as a local variable and access it like that, e.g.

for (let i = 0; i < str.length; i++) {...}
//vs
const len = str.length;
for (let i = 0; i < len; i++) {...}

Perhaps this is a redundant question in modern browsers, but I was curious because I have been doing some Leetcode questions and was looking at ways of improving the performance of a given solution. You are able to "resubmit" your questions and get a seemingly arbitrary "score" so it's difficult to see whether it makes a difference or not.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
liamw9
  • 527
  • 2
  • 6
  • 19
  • See also [Javascript For-Loop Condition Caching](https://stackoverflow.com/q/25816643/215552) and [Why for loop with cached length is slower than simple for loop?](https://stackoverflow.com/q/49327359/215552) – Heretic Monkey Nov 29 '22 at 19:07

0 Answers0