var n = 10;
function Person(name, age) {
this.name = name;
this.age = age;
}
var arr = [
new Person(1 + '', 24),
new Person(2 + '', 24),
new Person(3 + '', 24),
new Person(4 + '', 24),
new Person(5 + '', 24),
new Person(6 + '', 24),
new Person(7 + '', 24),
new Person(8 + '', 24),
new Person(9 + '', 24),
new Person(10 + '', 24)
].join(',');
var arr = [];
arr.push (new Person(1 + '', 24));
arr.push (new Person(2 + '', 24));
arr.push (new Person(3 + '', 24));
arr.push (new Person(4 + '', 24));
arr.push (new Person(5 + '', 24));
arr.push (new Person(6 + '', 24));
arr.push (new Person(7 + '', 24));
arr.push (new Person(8 + '', 24));
arr.push (new Person(9 + '', 24));
arr.push (new Person(10 + '', 24));
arr.join(',');
var arr = [];
arr.push (
new Person(1 + '', 24),
new Person(2 + '', 24),
new Person(3 + '', 24),
new Person(4 + '', 24),
new Person(5 + '', 24),new Person(6 + '', 24),new Person(7 + '', 24),
new Person(8 + '', 24),new Person(9 + '', 24),new Person(10 + '', 24)
);
arr.join(',');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
direct addition | |
Array.push without comma | |
Array.push with comma |
Test name | Executions per second |
---|---|
direct addition | 296931.3 Ops/sec |
Array.push without comma | 299300.9 Ops/sec |
Array.push with comma | 312266.2 Ops/sec |
Let's dive into the explanation of the benchmark.
Benchmark Definition:
The benchmark is designed to measure the performance of the Array.push
method in JavaScript. The script preparation code defines a Person
constructor, and the HTML preparation code is empty (i.e., no extra HTML elements are generated). The benchmark definition consists of three test cases:
Person
objects is created directly inside the Array.push
method.Person
objects is created and then passed to Array.push
, which then adds each object individually using the comma operator.Person
objects is created, but with commas separating each object before being passed to Array.push
.Options Compared:
The benchmark compares three different approaches for adding elements to an array using Array.push
. The options are:
Array.push
method.Array.push
, which adds each element individually.Array.push
.Pros and Cons of Each Approach:
Array.push
, which adds each element individually.Library and Purpose:
None of the benchmark cases use any external libraries. The Person
constructor is a simple JavaScript class defined within the script preparation code.
Special JS Features or Syntax:
The only special feature used here is the comma operator (,
) in Test Case 2, which creates an array by separating elements with commas. This syntax can be useful for creating arrays or objects with multiple values.
Other Considerations:
Array.push
for different approaches.Alternatives:
Other alternatives for benchmarking array push performance might include: