const n = 10000
var arr = new Array(n).fill(0);
for (let i = 0; i < n; i++) {
arr[i] = i;
}
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push({
x: arr[i],
y: arr[i] + 1
});
}
const result = [];
const obj = { x: 0, y: 0 };
for (let i = 0; i < arr.length; i++) {
obj.x = arr[i];
obj.y = arr[i] + 1;
result.push(obj);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Dynamic Creation | |
Pooling |
Test name | Executions per second |
---|---|
Dynamic Creation | 6140.5 Ops/sec |
Pooling | 11826.9 Ops/sec |
Let's break down the JavaScript microbenchmark you provided.
Benchmark Definition
The benchmark tests two approaches to create arrays of objects:
arr
with 10,000 elements and fills it with zeros. Then, for each element in the array, a new object is created and added to an empty result array.arr
array, a new object is created on the fly using the elements from arr
, and then that object is pushed into the result array.Options Compared
The benchmark compares two options:
Pros and Cons
Library Usage
There are no libraries explicitly mentioned in this benchmark, but it's worth noting that if a library were used to implement these approaches (e.g., Lodash or Array.prototype.map()), the results might differ due to the additional overhead of the library.
Special JS Features/Syntax
None of the provided benchmark code uses any special JavaScript features or syntax. It only uses basic JavaScript constructs like arrays, loops, and object creation.
Alternative Approaches
Other approaches to creating arrays of objects could include:
Array.prototype.map()
: Instead of using a loop to create new objects, you could use the map()
method to create an array of transformed objects. This approach is often more concise and efficient.map()
function: Similar to the previous suggestion, using a library's implementation of map()
can provide a performance boost compared to the basic JavaScript implementation.Keep in mind that these alternative approaches might have different performance characteristics depending on the specific use case and requirements.