class Basic {
obj = {};
add(k, v) {
this.obj[k] = v;
}
getValues() {
return Object.values(this.obj);
}
};
class Cached {
obj = {};
cache = [];
add(k, v) {
this.obj[k] = this.cache.length;
this.cache.push(v);
}
getValues() {
return this.cache;
}
};
basic = new Basic();
cached = new Cached();
for (let i = 0; i < 1000; i++) {
basic.add('a' + i, i);
cached.add('a' + i, i);
}
basic.getValues()
cached.getValues()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Fetch vias Object.values() | |
Fetch via cached array |
Test name | Executions per second |
---|---|
Fetch vias Object.values() | 105617.7 Ops/sec |
Fetch via cached array | 9609163.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Overview
The benchmark compares two approaches to fetching values from an object: Object.values()
and a cached array. The test creates two classes, Basic
and Cached
, which simulate these two approaches. Each class has methods to add key-value pairs to the object and retrieve the values using one of the two approaches.
What's being tested
The benchmark is testing the performance of these two approaches:
Object.values()
: This approach involves calling the getValues()
method on an object, which returns an array containing all the values in the object.getValues()
is called.Options compared
The benchmark is comparing two options:
Pros and cons of each approach:
values()
methodgetValues()
Library
In this benchmark, no external libraries are used. The Object.values()
method is a built-in JavaScript method.
Special JS feature/syntax
The benchmark uses ES6 syntax (e.g., arrow functions, classes) and modern JavaScript features (e.g., template literals). If you're using an older version of JavaScript that doesn't support these features, you may need to modify the code accordingly.
Other alternatives
While Object.values()
is a common approach for fetching values from an object, other alternatives include:
In terms of benchmarking, you might also consider testing other approaches, such as:
for...in
loops instead of Object.values()
I hope this explanation helps!