We indeed can and do hoist array.length if we can observe it definitely
doesn't change. In the micro-benchmark provided we definitely can:

test.js:
function test_arr_length() {
  var arr =
[1,2,3,4,5,6,8,43,43,4,432,432,432,432,432,432,432,32,542543,6536,5354,5,2532,432,4546,36,345,243,4,436,5,6545,432,4];

  var start = new Date();
  for (var i=0; i<10000000; i++) {
    for(var j=0; j<arr.length; j++){}
  }
  print("arrlen: " + (new Date() - start));
}

function test_variable() {
  var arr =
[1,2,3,4,5,6,8,43,43,4,432,432,432,432,432,432,432,32,542543,6536,5354,5,2532,432,4546,36,345,243,4,436,5,6545,432,4];

  var start = new Date();
  for (var i=0; i<10000000; i++) {
    for(var j=0,len=arr.length; j<len; j++){}
  }
  print("variable: " + (new Date() - start));
}

test_arr_length();
test_variable();

output:
arrlen: 200
variable: 204

Note with this example the result can sometimes jump to 300 for one or both
tests.

This is really micro micro benchmarking. I mean the difference you measure
possibly isn't because we output different code, but due to processor
handling of the code.

grtz Hannes


On Mon, Jan 20, 2014 at 7:45 PM, Brendan Eich <[email protected]> wrote:

> Jan, anyone:
>
> https://twitter.com/phidip/status/425337790872973312
>
> "In JS array.length is a property. Why is for(i=0;i<array,length;i++){}
> slower than for(i=0,len=array,length;i<len;i++){} ?"
>
> Feel free to contact Niels directly (http://wefollow.com/phidip). Thanks,
>
> /be
> _______________________________________________
> dev-tech-js-engine-internals mailing list
> [email protected]
> https://lists.mozilla.org/listinfo/dev-tech-js-engine-internals
>
_______________________________________________
dev-tech-js-engine-internals mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-tech-js-engine-internals

Reply via email to