function getRandomElement(id) {
return {
id,
a: Math.random(),
b: Math.random(),
c: Math.random(),
}
}
function getArray(length) {
const result = [];
for (let i = 0; i < length; i++) {
result.push(getRandomElement(i))
}
return result;
}
array_small = getArray(10000);
array_large = getArray(1000000);
const found = array_small.find(function(element) {
return element.id == 9999;
});
found.a = 9999;
const array = array_small.map(function(element) {
if (element.id == 9999) {
element.a = 9999;
}
return element;
});
const found = array_large.find(function(element) {
return element.id == 999999;
});
found.a = 999999;
const array = array_large.map(function(element) {
if (element.id == 999999) {
element.a = 999999;
}
return element;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Find small array | |
Map small array | |
Find large array | |
Map large array |
Test name | Executions per second |
---|---|
Find small array | 73252.1 Ops/sec |
Map small array | 33151.6 Ops/sec |
Find large array | 164.9 Ops/sec |
Map large array | 133.7 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what is being tested.
Benchmark Definition
The benchmark definition provides two different approaches for finding or mapping an element in an array of objects:
find()
: This method returns the first element that satisfies the provided condition (in this case, finding an object with a specific id
).map()
: This method creates a new array with the results of applying the provided function to each element in the original array.Options Compared
The benchmark is comparing the performance of these two approaches for both small and large arrays.
Pros and Cons of Each Approach:
find()
to ensure it's the desired element.Other Considerations:
find()
method uses the built-in Array.prototype.find() function, which is a part of the ECMAScript standard.Alternatives:
If you need to find or map elements in an array, consider using other methods:
filter()
: Returns a new array with all elements that satisfy the condition.forEach()
: Executes a function for each element in the array without returning a new array.reduce()
: Accumulates values in an array while applying a function to each element.Keep in mind that these alternatives may have different performance characteristics, memory usage, and use cases depending on your specific requirements.
As a software engineer, it's essential to consider the trade-offs between different approaches and choose the one that best suits your needs. In this case, the benchmark highlights the importance of considering performance and memory usage when selecting an algorithm for finding or mapping elements in an array.