var x = new Float32Array(1000000),
y = new Float32Array(1000000),
z = new Float32Array(1000000);
var vectors = [];
for (var i = 0; i < 1000000; i++) {
x[i] = Math.random() * 100;
y[i] = Math.random() * 100;
z[i] = Math.random() * 100;
vectors[i] = {
x: x[i],
y: y[i],
z: z[i]
};
}
var vector;
for (var i = 0, li=x.length; i < li; ++i) {
x[i] = 2 * x[i];
y[i] = 2 * y[i];
z[i] = 2 * z[i];
}
for (var i = 0, li=vectors.length; i < li; ++i) {
vector = vectors[i];
vector.x = 2 * vector.x;
vector.y = 2 * vector.y;
vector.z = 2 * vector.z;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
soa | |
aos |
Test name | Executions per second |
---|---|
soa | 629.7 Ops/sec |
aos | 257.1 Ops/sec |
What is being tested?
The provided benchmark tests the performance difference between two approaches to iterating over data in JavaScript:
length
property, accessing each element by index (x[i]
, y[i]
, z[i]
). The loop variable i
is incremented manually.for...in
loop to iterate over an array's indices and then accesses each element through the array object itself (vectors[i]
, vector.x
, vector.y
, vector.z
). The loop variable is still i
.Options compared
The two approaches differ in how they access and manipulate elements within the arrays:
i
, which can lead to off-by-one errors or other issues if not managed carefully.for...in
loop.Library usage
None of the provided benchmark definitions use a specific JavaScript library. However, the Float32Array
data structure is used, which is part of the JavaScript standard library (ECMAScript).
Special JS features or syntax
The benchmarks utilize the following special feature:
for
loops with let i = 0;
, these benchmarks use for...in
loops to iterate over array indices. This can lead to unexpected behavior if not used carefully, as it may access properties that are not intended to be iterated.Other alternatives
Alternative approaches to iterating over arrays in JavaScript include:
for (var i = 0; i < array.length; i++)
Float32Array
with custom iterator protocols can offer better performance than traditional array iteration.