var x = [], y =[], z =[];
var vectors = [];
for(var i = 0; i < 1000000; i++){
x[i] = Math.random()*100|0;
y[i] = Math.random()*100|0;
z[i] = Math.random()*100|0;
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;
}
for (var i = 0, li=x.length; i < li; ++i) {
x[i] = 2 * x[i];
}
for (var i = 0, li=x.length; i < li; ++i) {
y[i] = 2 * y[i];
}
for (var i = 0, li=x.length; i < li; ++i) {
z[i] = 2 * z[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
soa | |
aos | |
soa mark II |
Test name | Executions per second |
---|---|
soa | 1.5 Ops/sec |
aos | 1.0 Ops/sec |
soa mark II | 1.5 Ops/sec |
Measuring the performance difference between Single-Op Arrays (SoA) and Array-Of-Arrays (AoA) is a common benchmark in JavaScript.
What are SoA and AoA?
Single-Op Arrays (SoA) store all three arrays (x
, y
, and z
) together as separate elements of an array, where each element is an object containing the corresponding values. This approach is often used when working with large datasets.
Array-Of-Arrays (AoA), on the other hand, use individual arrays for each variable. In this case, there are three separate arrays: one for x
, one for y
, and one for z
. Each of these arrays stores only its own values.
Options Compared
In this benchmark, two variants of SoA (SoA) and AoA (AoA Mark II) are compared:
x
, y
, and z
) as separate objects.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Pros:
Cons:
Pros:
Cons:
Library and Special JS Features
This benchmark does not explicitly use any libraries or special JavaScript features beyond standard ES6 syntax.
Considerations
When working with large datasets in JavaScript, it's essential to consider memory efficiency and performance. While SoA can be beneficial for memory usage, AoA Mark II offers faster access times at the cost of increased memory consumption. The choice between these two approaches depends on your specific use case and priorities.
Alternatives
If you're interested in exploring alternative approaches or optimizing your code further, consider the following:
Float64Array
) can provide better performance and memory efficiency.Uint8ClampedArray
) can offer improved performance by reducing the number of cache accesses.