1

I'm an front end webdev intern at a small company where I'm making a panel which displays database statistics.

Now I noticed that on my panel which gives the count for how many entries are in a specific array the specific stat always takes a while to load (my other statistics appear nearly instantly).

Now my question is, does array.length actually loop though the whole array to get it's length? The length is about 17000 and takes about 5 seconds to appear so I'm guessing that's the time it takes to loop through such a big array.

jmargolisvt
  • 5,722
  • 4
  • 29
  • 46
Jari
  • 31
  • 4
  • Make SURE you do this in a for loop: `for (var i=0,n=arr.length;i – mplungjan Jun 08 '18 at 20:35
  • In which browser are you seeing this? – christopher Jun 08 '18 at 20:35
  • No. It does not. var arr = []; arr[0] = 1; arr[1000000000] = 2; var start = Date.now(); var len = arr.length; var timeUsed = Date.now() - start; console.log('Length:', len, 'Time used:', timeUsed); See how long that took? 0. – oligofren Jun 08 '18 at 20:36
  • With large arrays I agree with @mplungjan and explicitly set the length so on each iteration `.length` isn't checked. However, I'd like to say it depends on what you're actually doing in the loop as many JavaScript engines are good at optimizing these things. – Phix Jun 08 '18 at 20:39

1 Answers1

1

It is implementation dependent. The optimal implementation should know its length, where as the lazy one would iterate to figure this out.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 2
    I don't think this is true. `length` is a regular property of Arrays, it's assignable. No implementation is free to dynamically compute it. You can assign any integer to the `length` property to grow or shrink the array. – user229044 Jun 08 '18 at 20:36
  • @meagar - if you add or remove stuff from the array the length will change – mplungjan Jun 08 '18 at 20:36
  • 1
    @mplungjan Yes, because the array will update the length property on itself as you add or remove elements, but it does *not* dynamically compute the length. – user229044 Jun 08 '18 at 20:37