var obj = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
g: 7,
h: 8,
i: 9,
j: 10,
k: 11,
l: 12,
m: 13,
n: 14,
o: 15,
p: 16,
q: 17,
r: 18,
s: 19,
t: 20,
u: 21,
v: 22,
w: 23,
x: 24,
y: 25,
z: 26
};
var map = new Map(Object.entries(obj));
Object.values(obj).reduce(function(total, value) {
return total + value;
}, 0);
let total = 0;
for (const key in obj) {
total += obj[key];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.entries() - forEach | |
Object - for in |
Test name | Executions per second |
---|---|
Object.entries() - forEach | 1152987.2 Ops/sec |
Object - for in | 323020.6 Ops/sec |
The provided JSON represents two benchmark test cases: Object iteration using for...in
loop and values()
method, and Object.entries()
with forEach()
method.
Options being compared:
for...in
loop: This is an traditional way of iterating over object properties in JavaScript.values()
method: Introduced in ECMAScript 2019, this method returns a new iterable that contains the values of the given object.Pros and Cons of each approach:
for...in
loop:values()
method:Library:
None of the test cases use any external libraries.
Special JS feature or syntax:
for...in
loop uses a traditional JavaScript syntax.values()
method is a modern JavaScript feature introduced in ECMAScript 2019.Benchmark Preparation Code:
The preparation code creates an object obj
with 26 properties and initializes a new Map
instance from the object's entries using Object.entries()
. This allows for direct comparison of the two iteration methods.
Other alternatives:
for
loop with a counter variable.for...in
loop may be a better choice.Object.entries()
method and forEach()
method can also be used together to achieve similar results.It's worth noting that the test cases are designed to compare the performance of different iteration methods in a controlled environment, which is useful for optimizing JavaScript code.