const a = [];
for( let i=0; i<100000;i++ ) a.push( Math.random() );
const a = [];
for( let i=0; i<100000;i++ ) a[ a.length] = Math.random();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
a | |
b |
Test name | Executions per second |
---|---|
a | 50.5 Ops/sec |
b | 51.8 Ops/sec |
I'd be happy to explain the benchmark and its results.
What is being tested?
The provided JSON represents two individual test cases for a JavaScript microbenchmark: Array push vs
. The goal of this benchmark is to compare the performance of two different ways of pushing elements onto an array in JavaScript.
Options being compared
There are two options being compared:
a.push(Math.random())
: This option uses the push()
method to add a new element to the end of the array.a[a.length] = Math.random()
: This option uses the syntax a[a.length] = ...
to access and assign a value to the last index of the array.Pros and Cons of each approach
a.push(Math.random())
:push()
method's internal implementation.a[a.length] = Math.random()
:undefined
or null
values).Other considerations
Math.random()
to generate random numbers introduces additional overhead due to the cost of generating random numbers.Library usage
None of the provided code snippets use any external libraries.
Special JS features or syntax
There are no special JavaScript features or syntax used in these benchmark tests. They only rely on standard JavaScript syntax and built-in functions.
Alternatives
If you need to compare other aspects of array manipulation, such as:
a[0] = ...
: Accessing the first element of an array.a.indexOf(...)
: Finding a specific value in an array.Array.prototype.forEach()
: Iterating over an array using a callback function.You can create additional test cases to compare these different approaches.