Array.at vs length - 1

Benchmark created on


Description

Comparison of Array.at vs length - 1.

Setup

// We cannot use floating point numbers, since their operations are not actually associative, so we make them all integers
let array = new Array(100000).fill(0).map(() => ~~(Math.random() * 100));

let sum = array.reduce((lhs, rhs) => lhs + rhs);

Teardown

array.length = 0;

Test runner

Ready to run.

Testing in
TestOps/sec
Backwards sum with .length
let mySum = 0;
for(let i = 0; i < array.length; i++) {
	mySum += array[array.length - 1 - i];
}

if(mySum != sum) {
	throw new Error("Uhhh")
}
ready
Backwards sum with .at
let mySum = 0;
for(let i = 0; i < array.length; i++) {
	mySum += array.at(-i);
}

if(mySum != sum) {
	throw new Error("Uhhh")
}
ready
Forwards with .length
let mySum = 0;
for(let i = 0; i < array.length; i++) {
	mySum += array[i];
}

if(mySum != sum) {
	throw new Error("Uhhh")
}
ready
Forwards with cached .length
let mySum = 0;
for(let i = 0, len = array.length; i < len; i++) {
	mySum += array[i];
}

if(mySum != sum) {
	throw new Error("Uhhh")
}
ready
Forwards with let of
let mySum = 0;
for(let item of array) {
	mySum += item;
}

if(mySum != sum) {
	throw new Error("Uhhh")
}
ready
Forwards with var of
let mySum = 0;
for(var item of array) {
	mySum += item;
}

if(mySum != sum) {
	throw new Error("Uhhh")
}
ready
Forwards with const of
let mySum = 0;
for(const item of array) {
	mySum += item;
}

if(mySum != sum) {
	throw new Error("Uhhh")
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.