const getData = () => [Array.from(Array(5000))].map(_ => ({
a: 123,
b: '123',
c: [1, 2, 3]
}));
const getData = () => [Array.from(Array(5000))].map(_ => ({ a: 123, b: '123', c: [1,2,3]}));
const concatTest = () => {
const a = getData();
const b = a.concat(getData());
}
concatTest();
const getData = () => [Array.from(Array(5000))].map(_ => ({ a: 123, b: '123', c: [1,2,3]}));
const spreadTest = () => {
const a = getData();
const b = [a, getData()]
}
spreadTest();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
concat | |
spread |
Test name | Executions per second |
---|---|
concat | 2647.4 Ops/sec |
spread | 2099.4 Ops/sec |
I'll break down the provided benchmark definition and test cases, explaining what's being tested, the pros and cons of each approach, and other considerations.
Benchmark Definition
The benchmark measures the performance difference between three ways to concatenate objects in JavaScript:
concat()
...
)The script preparation code generates an array of 5000 objects with specific properties (a string, a number, and an array) for each test case.
Test Cases
There are two test cases:
concat
const getData = () => [...Array.from(Array(5000))].map(_ => ({ a: 123, b: '123', c: [1,2,3]}));
const concatTest = () => {
const a = getData();
const b = a.concat(getData());
}
This test case uses the concat()
method to concatenate two arrays of objects. The concat()
method creates a new array and copies all elements from both arrays into it.
spread
const getData = () => [...Array.from(Array(5000))].map(_ => ({ a: 123, b: '123', c: [1,2,3]}));
const spreadTest = () => {
const a = getData();
const b = [...a, ...getData()];
}
This test case uses the spread syntax (...
) to concatenate two arrays of objects. The ...
operator creates a new array with all elements from both arrays.
Options Compared
The benchmark compares the performance of three options:
concat()
method to create a new array and copy all elements from both arrays....
): Uses the spread syntax to concatenate two arrays into a single array.Pros and Cons
...
):concat()
or a temporary variable.concat()
due to reduced overhead of creating new arrays.Library Usage
None of the test cases uses any external libraries or frameworks. The benchmark only relies on built-in JavaScript features.
Special JS Features or Syntax
The benchmark uses the following special JavaScript features:
...
): Used for array concatenation and spread operation.getData()
function to create a template literal.Alternatives
If you want to measure the performance of other approaches, consider using different test cases or modifying the existing ones. For example:
Keep in mind that benchmarking JavaScript performance can be complex, and results may vary depending on the specific use case and environment.