var sorted = new Array(200000);
var shuffled = new Array(200000);
class Vector {
constructor() {
this.x = 0;
this.y = 0;
this.z = 0;
}
}
for (let i=0; i<200000; i++) {
const obj = { position: new Vector(), scale: new Vector(), rotation: new Vector() };
sorted[i] = obj;
shuffled[i] = obj;
}
for (let i=0; i<200000; i++) {
const index = Math.floor(Math.random() * 200000);
const temp = shuffled[i];
shuffled[i] = shuffled[index];
shuffled[index] = temp;
}
for (let i=0; i<200000; i++) {
const obj = shuffled[i];
if (obj.position.x === 0 && obj.position.y === 0 && obj.position.z === 0) {}
}
for (let i=0; i<200000; i++) {
const obj = shuffled[i];
const position = obj.position;
if (position.x === 0 && position.y === 0 && position.z === 0) {}
}
for (let i=0; i<200000; i++) {
const obj = sorted[i];
if (obj.position.x === 0 && obj.position.y === 0 && obj.position.z === 0) {}
}
for (let i=0; i<200000; i++) {
const obj = sorted[i];
const position = obj.position;
if (position.x === 0 && position.y === 0 && position.z === 0) {}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Shuffled | |
Shuffled const | |
Sorted | |
Sorted const |
Test name | Executions per second |
---|---|
Shuffled | 25.0 Ops/sec |
Shuffled const | 25.9 Ops/sec |
Sorted | 67.9 Ops/sec |
Sorted const | 69.0 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark is designed to measure the performance of JavaScript engines in comparing two arrays: sorted
and shuffled
. The arrays contain 200,000 objects with three vectors (x, y, z) each.
The script preparation code creates both arrays and shuffles the second array using a Fisher-Yates shuffle algorithm. This ensures that the order of elements is randomized.
Options Compared
There are four test cases:
const
keyword when comparing the shuffled array elements with their positions.const
keyword when comparing the sorted array elements with their positions.Pros and Cons of Each Approach
const
, the comparison is made only when necessary (i.e., when an element doesn't match its position). This reduces unnecessary computations and makes it faster than Shuffled
.Shuffled
, this approach finds identical pairs more frequently, making it slower due to unnecessary comparisons.Shuffled const
, this approach uses const
for efficient comparisons.Special JS Features/Syntax
There are no specific JavaScript features or syntaxes being tested in this benchmark. However, the use of class
and object literals (const obj = { position: new Vector(), scale: new Vector(), rotation: new Vector() }
) is typical for modern JavaScript development.
Alternatives
Other alternatives to test array comparison performance could include:
every()
or some()
methods.The provided benchmark is designed to measure the efficiency of JavaScript engines in performing simple array comparison tasks.