<!--your preparation HTML code goes here-->
class Vec2_int {
x = 0;
y = 0;
randomize() {
this.x = Math.random();
this.y = Math.random();
}
length2() {
return this.x * this.x + this.y * this.y;
}
length() {
return Math.sqrt(this.length2());
}
}
let num = 10000
let sum = 0
for (let i=0; i<num; i++) {
let v = new Vec2_int();
v.randomize();
sum += v.length();
}
sum /= num;
console.log(sum);
class Vec2_float {
x = 0.5;
y = 0.5;
randomize() {
this.x = Math.random();
this.y = Math.random();
}
length2() {
return this.x * this.x + this.y * this.y;
}
length() {
return Math.sqrt(this.length2());
}
}
let num = 10000
let sum = 0
for (let i=0; i<num; i++) {
let v = new Vec2_float();
v.randomize();
sum += v.length();
}
sum /= num;
console.log(sum);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Vec2_int | |
Vec2_float |
Test name | Executions per second |
---|---|
Vec2_int | 294.2 Ops/sec |
Vec2_float | 288.0 Ops/sec |
The benchmark defined here is focused on comparing the performance of two different implementations of a 2D vector class, Vec2_int
and Vec2_float
, which represents mathematical vectors. The two classes differ primarily in how they define their properties.
Vec2_int:
x
and y
are initialized to integers (0
).randomize()
: Assigns random float values to x
and y
.length2()
: Computes the squared length of the vector.length()
: Computes the actual length using the square root of the squared length.Vec2_int
are created, random values assigned, and the lengths are calculated and averaged.Vec2_float:
x
and y
are initialized to floats (0.5
).Vec2_int
.Vec2_int
, 10,000 instances are created, random values assigned, and lengths are calculated.0.5
) might provide an initial value closer to what would realistically be used in vector calculations (e.g., graphics, physics), where floating-point precision is crucial.Vec2_float
: 944.72 executions/second.Vec2_int
: 913.15 executions/second.Vec2_float
implementation outperformed Vec2_int
by a small margin.Vec2_float
a more suitable choice for practical applications.Float32Array
or Float64Array
can be more efficient. These typed arrays offer a way to work with binary data and provide better performance for numerical calculations.In summary, while the benchmark is primarily about testing performance under similar mathematical operations, the choice of using integers vs. floats can lead to significant differences in practical applications, with the latter typically providing better performance and accuracy for vector operations.