function addObj(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
out[2] = a[2] + b[2];
return out;
};
function addArr(out, oo, a, b, ao,bo) {
out[0+oo] = a[0+ao] + b[0+bo];
out[1+oo] = a[1+ao] + b[1+bo];
out[2+oo] = a[2+ao] + b[2+bo];
};
function addArr2(out, a, b, oo, ao,bo) {
out[0+(oo || 0)] = a[0+(ao || 0)] + b[0+(bo || 0)];
out[1+(oo || 0)] = a[1+(ao || 0)] + b[1+(bo || 0)];
out[2+ (oo || 0)] = a[2+(ao || 0)] + b[2+(bo || 0)];
};
var A = new Float32Array(3000);
var B = new Float32Array(3000);
var O = new Float32Array(3000);
for (var i = 0;i < 10000;++i) {
for (var j=0;j< 1000;++j) {
addArr(O,j*3,A,B,j*3,j*3);
}
}
var A = [];
var B = [];
var O = [];
for (var x=0;x<1000;++x) {
A.push(new Float32Array(3));
B.push(new Float32Array(3));
O.push(new Float32Array(3));
}
for (var i = 0;i < 10000;++i) {
for (var j=0;j< 1000;++j) {
addObj(O[j],A[j],B[j]);
}
}
var A = new Float32Array(3000);
var B = new Float32Array(3000);
var O = new Float32Array(3000);
for (var i = 0;i < 10000;++i) {
for (var j=0;j< 1000;++j) {
addArr2(O,A,B,j * 3,j*3,j*3);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
vec3 Arr | |
vec3 obj | |
vec3 arr2 |
Test name | Executions per second |
---|---|
vec3 Arr | 0.6 Ops/sec |
vec3 obj | 0.7 Ops/sec |
vec3 arr2 | 0.4 Ops/sec |
Benchmark Explanation
MeasureThat.net provides a platform for creating and running JavaScript microbenchmarks to compare the performance of different approaches to solving a specific problem. In this case, we have three individual test cases that measure the performance of adding vectors (3D coordinates) in various ways.
Test Cases
addArr
function, which adds corresponding elements from two arrays to a third array.addObj
function, which adds corresponding properties of two objects to a third object.vec3 Arr
, but it uses a modified version of the addArr2
function with optional default values.Library: Float32Array
The benchmark uses Float32Array
as a data structure for storing and manipulating floating-point numbers. A Float32Array
is a typed array that represents an array of 32-bit floating-point numbers.
Special JS Feature/Syntax
There are no specific JavaScript features or syntax used in this benchmark, but it does utilize the concept of closures (i.e., the use of var
to declare variables within the scope of a function).
Options Compared
The three test cases compare the performance of adding vectors using different data structures:
vec3 Arr
and vec3 arr2
use arrays as input/output data structures.vec3 obj
uses objects as input/output data structures.Pros and Cons of Different Approaches
addArr
.Other Alternatives
Some other alternatives for adding vectors in JavaScript might include:
mathjs
or vec3.js
, which provide optimized vector arithmetic functions and data structures.