<!--your preparation HTML code goes here-->
/*your preparation JavaScript code goes here
To execute async code during the script preparation, wrap it as function globalMeasureThatScriptPrepareFunction, example:*/
async function globalMeasureThatScriptPrepareFunction() {
// This function is optional, feel free to remove it.
// await someThing();
}
var a = new Float32Array([1,2,3]);
var a = new Float32Array(3);
a[0] = 1;
a[1] = 2;
a[2] = 3;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array | |
No Array |
Test name | Executions per second |
---|---|
Array | 9333970.0 Ops/sec |
No Array | 27135936.0 Ops/sec |
The benchmark defined in the provided JSON is centered around the initialization of Float32Array
in JavaScript, specifically comparing two different ways of initializing and populating this typed array: using an inline array versus manual assignment.
Initialization using an inline Array:
var a = new Float32Array([1,2,3]);
Float32Array
with an array literal, where values are provided directly in an array format. This method is straightforward and can be perceived as more readable.Initialization without an inline Array:
var a = new Float32Array(3);
a[0] = 1;
a[1] = 2;
a[2] = 3;
Float32Array
is created with a specified length (3), and its values are assigned manually in subsequent statements. This method offers granular control over each element but may be viewed as slightly less convenient.The benchmark results reveal how each method performs in terms of execution speed, measured in "Executions Per Second". The performance outcomes are as follows:
Pros:
Cons:
Pros:
Cons:
In this benchmark, no external libraries are tested, nor is there any unique JS feature or syntax that is leveraged beyond standard ECMAScript capabilities.
Alternative approaches to initializing an array in JavaScript might include:
Array.from:
var a = Float32Array.from([1, 2, 3]);
Spread Operator:
var arr = [1, 2, 3];
var a = new Float32Array(...arr);
Float32Array
. While this is similar to the inline method, it can offer more flexibility with dynamic arrays.Using a Loop:
var a = new Float32Array(3);
for (let i = 0; i < a.length; i++) {
a[i] = i + 1; // Assign values dynamically
}
This benchmark serves to highlight the trade-offs between readability and raw performance when deciding how to initialize typed arrays in JavaScript. Depending on application needs—whether prioritizing performance or code clarity—developers can choose the most suitable approach. The provided alternatives also offer additional flexibility for various coding scenarios.