var object = {};
for (let i = 1; i <= 100000; i++) object[String(i)] = i;
Object.keys(object).length
let i = 0; for (const k in object) i++;
Object.entries(object).length
Object.values(object).length
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.keys().length | |
for in i++ | |
Object.entries().length | |
Object.values().length |
Test name | Executions per second |
---|---|
Object.keys().length | 514.6 Ops/sec |
for in i++ | 426.1 Ops/sec |
Object.entries().length | 199.4 Ops/sec |
Object.values().length | 4148.4 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of different methods to iterate over an object in JavaScript:
Object.keys()
+ .length
for...in
loop with i++
Object.entries()
+ .length
Object.values()
+ .length
Options Comparison
Each option has its pros and cons:
Object.keys().length
: This method is concise and easy to read, but it may not be the fastest approach because it returns an array of keys without any iteration.for...in
loop with i++
: This method can iterate over the object's properties, but it has a slower performance compared to other methods due to the unnecessary increment operation. However, it allows for more control and flexibility in iterating over the object's properties.Object.entries()
+ .length
: This method returns an array of key-value pairs, allowing for iteration over both keys and values. It is generally faster than for...in
loop with i++
, but may not be as concise.Object.values()
+ .length
: This method returns only the object's values, making it suitable when you need to iterate only over the values. However, it may not be suitable for cases where you also need to access the corresponding keys.Library and Special JS Feature
The provided benchmark uses no specific libraries or special JavaScript features other than the built-in Object
methods.
Benchmark Preparation Code
The script preparation code creates a large object with 100,000 properties and assigns each property an integer value. This allows for high-performance iterations over the object's properties.
Other Alternatives
If you're looking for alternative approaches to measure performance in JavaScript, consider:
for...of
loop: Introduced in ECMAScript 2015 (ES6), for...of
loops provide a more concise and readable way to iterate over arrays and iterables.reduce()
method: Another built-in method that allows for efficient iteration and aggregation of data.Keep in mind that the choice of approach depends on your specific use case and requirements.