var items = Array.from(Array(1000), (_, x) => ({
key: x,
value1: Math.random() * 1000,
value2: Math.random() * 1000
}));
var objContainer = {};
var arrContainer = [];
for (let i = 100; i >= 0; i--) {
const index = Math.floor(Math.random() * 1000);
const item = items[index];
objContainer[item.key] = item;
arrContainer.push(item)
}
var result = [];
for (var k in objContainer) {
if (objContainer[k].value1 >= 0 && objContainer[k].value1 <= 499 && objContainer[k].value2 >= 500 && objContainer[k].value2 <= 999) {
result.push(k);
}
}
var result = [];
for (var item of arrContainer) {
if (item.value1 >= 0 && item.value1 <= 499 && item.value2 >= 500 && item.value2 <= 999) {
result.push(item.key);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Get array of keys with value 1 between 0 and 499, and value 2 between 500 and 999 in Object | |
Get array of keys with value 1 between 0 and 499, and value 2 between 500 and 999 in Array |
Test name | Executions per second |
---|---|
Get array of keys with value 1 between 0 and 499, and value 2 between 500 and 999 in Object | 30161.8 Ops/sec |
Get array of keys with value 1 between 0 and 499, and value 2 between 500 and 999 in Array | 2424853.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
The provided JSON represents a benchmark test case created on MeasureThat.net. The goal is to compare the performance of two approaches: object value comparison vs array find.
Options being compared:
for...in
loop to iterate over the keys of an object and checks if the values satisfy the specified condition.find()
method on an array to find elements that satisfy the specified condition.Pros and Cons:
Other considerations:
Benchmark Definition
is quite specific (value 1 between 0 and 499, value 2 between 500 and 999), which may not be representative of real-world scenarios.Library/Language features:
The benchmark uses no external libraries or language features that are not part of the standard JavaScript specification. It relies on built-in methods like Array.from()
, for...in
, and find()
.
Special JS feature/syntax:
There are no special JS features or syntax used in this benchmark. The code is written in plain JavaScript, using standard constructs and data structures.
Now, let's look at the latest benchmark results:
The two test cases show a significant performance difference between object value comparison and array find. The Object
test case executes approximately 242k times per second on Mobile Safari 15, while the Array
test case executes around 30k times per second. This suggests that array find is significantly faster for this particular use case.
Other alternatives to these approaches include:
Benchmark Definition
to reduce the number of iterations.Keep in mind that microbenchmarking is an art, and results may vary depending on specific use cases and environments.