var quantityOfElements = 100000000;
var array = new Array(quantityOfElements);
var quantityOfTests = 10000;
for (let i = 0; i < quantityOfElements; i++) {
array[i] = {
id: i
};
}
let map = new Map();
for (let i = 0; i < quantityOfElements; i++) {
map.set(array[i].id, array[i]);
}
let obj = {};
for (let i = 0; i < quantityOfElements; i++) {
obj[array[i].id] = array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map create | |
Object create |
Test name | Executions per second |
---|---|
Map create | 0.0 Ops/sec |
Object create | 0.7 Ops/sec |
I'll break down the benchmark and its test cases to explain what's being tested, compared, and the pros and cons of each approach.
Benchmark Overview
The MeasureThat.net benchmark measures the performance difference between creating objects using an array (Array
) versus an object (Object
).
Script Preparation Code
The script preparation code creates a large array array
with 100 million elements, each containing a single property id
. This array will be used to create objects in the test cases.
var quantityOfElements = 100000000;
var array = new Array(quantityOfElements);
for (let i = 0; i < quantityOfElements; i++) {
array[i] = { id: i };
}
Html Preparation Code
There is no HTML preparation code provided.
Test Cases
The benchmark consists of two test cases:
Map
object and sets elements from the array
to the map using the set()
method.let map = new Map();
for (let i = 0; i < quantityOfElements; i++) {
map.set(array[i].id, array[i]);
}
array
to the object using the syntax obj[array[i].id] = array[i];
.let obj = {};
for (let i = 0; i < quantityOfElements; i++) {
obj[array[i].id] = array[i];
}
What's being tested?
The benchmark tests the performance difference between creating objects using a Map
versus an object literal (Object
). The test focuses on the time it takes to create these objects and set elements from the same array.
Comparison of Map, Object, and Array
Map
object and setting elements using the set()
method requires more overhead than directly creating objects, as it involves additional operations like checking if keys already exist in the map.Pros and Cons
Special JS feature/Syntax
None mentioned in the benchmark, but keep in mind that certain JavaScript features or syntax might affect performance differently depending on the specific implementation. However, since this example doesn't involve any such features, we can focus solely on array vs object literal performance.
Other Alternatives
For most modern browsers, the array-based approach tends to perform better than both map and object literal approaches. However, performance differences may vary depending on the specific use case, the size of the data set, and the underlying hardware and software configurations.