var arraySize = 10000;
var iterations = arraySize + 100;
var data;
var operate = function(){
for(var index = 0; index < iterations; index++){
if(data.length == arraySize) data.pop();
data.unshift({});
}
}
data = new Array(arraySize);
operate();
data = [];
operate();
data = [];
data.length=arraySize;
operate();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new Array | |
brackets | |
brackets with length |
Test name | Executions per second |
---|---|
new Array | 33.9 Ops/sec |
brackets | 63.1 Ops/sec |
brackets with length | 10.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition JSON
The benchmark definition JSON provides information about the test case, including:
operate()
. The purpose of this function is to populate an array with empty objects.Test Cases
The test cases are defined in the following JSON:
[
{
"Benchmark Definition": "data = new Array(arraySize);\r\noperate();",
"Test Name": "new Array"
},
{
"Benchmark Definition": "data = [];\r\noperate();",
"Test Name": "brackets"
},
{
"Benchmark Definition": "data = [];\r\ndata.length=arraySize;\r\noperate();",
"Test Name": "brackets with length"
}
]
These test cases compare three different ways of creating an array in JavaScript:
new
keyword.[]
).length
property of an object that will be used as an array.Options Compared
The three test cases compare different ways of creating an array, which has implications for performance and code readability.
new Array
: Creates a new, empty array. Pros: more explicit creation, can be faster. Cons: requires more memory.[]
: Creates a new, empty array using square brackets. Pros: concise syntax, often preferred by developers. Cons: may be slower due to the need for extra processing.Array constructor with length assignment**: Assigns a value to the
length` property of an object that will be used as an array. Pros: can be faster and more memory-efficient than the other two options. Cons: requires explicit memory management, which can add complexity.new Array
or []
may also affect how JavaScript engines optimize array creation. Some engines may create arrays using a different allocation strategy that takes into account the type and size of the array.Library Used
None of the test cases explicitly uses any external libraries.
Special JS Features/Syntax
None, except for the use of const
in some parts of the benchmark definition code (e.g., "var data;"
is not present in the test cases).
Alternatives
Other alternatives to measure array creation performance might include:
Keep in mind that MeasureThat.net's focus is on comparing JavaScript engine performance, so alternatives might be less relevant to the specific use case.