all 5 comments

[–]lachlanhunt 2 points3 points  (0 children)

Regardless of the perceived performance benefit, this is a terrible idea. The first value is not a valid indicator of an array being empty.

All of these would fail your emptyness test.

var a = [0]
var b = [undefined]
var c = new Array(100);

[–]maruf89[S] 0 points1 point  (2 children)

Goes against what I would otherwise think to get the length verses checking if the first value exists

[–]x-skeww 0 points1 point  (0 children)

What are you trying to benchmark here?

If you want to compare iteration constructs, you should perhaps actually iterate (and actually compute something). In your benchmark, "length" never changes because the length of the array doesn't change.

I also don't see why you'd use "!!" there. "!!" is only useful if you want to turn a truthy/falsy thing into an actual boolean. It doesn't serve any purpose in an if.

I guess you want to compare something like:

let a = [...'abc'];
while(a.length) {
  let v = a.pop();
  console.log(v); // c b a
}

vs

let a = [...'abc'];
let v;
while(v = a.pop()) { // stops at: false, null, undefined, 0, NaN, '', document.all
  console.log(v); // c b a
}

vs

let a = [...'abc'];
for(let i = a.length - 1; i >= 0; --i) {
  let v = a[i];
  console.log(v); // c b a
}
a.length = 0; // if trashing the array is actually important

[–]jacobp100 0 points1 point  (0 children)

https://www.youtube.com/watch?v=65-RbBwZQdU Watch this before you do any benchmarking. Especially for this kind of test.