Recently, in a project, we had to extract the values from a large collection of objects and, while the easiest way to do so was to use the native Object.values()method, which returns an array of a given object’s own enumerable property values, we noticed some performance issues. So, we started measuring the performance of this method compared to some other options:

  • using the _.values() from the popular lodash library
  • or doing it in a more “traditional” way using the for...in loop.

To compare our results we used a simple object, e.g.: {a: 1, b: 2, c: 3}, with no other nested properties, and to measure the performance of each method we used the performance.now() method witch returns a DOMHighResTimeStamp measured in milliseconds.

Usage

let start = performance.now(); 

// code to be timed... 
let duration = performance.now() - start;

Test Cases

// --------------------
// Object.values()
// --------------------
let start = performance.now();

for (let i = 0; i < Math.pow(10, 9); i++) {
   Object.values({ a: 1, b: 2, c: 3 });
}

let duration = performance.now() - start;
console.log(duration);

// --------------------
// _.values()
// --------------------
let start = performance.now();

for (let i = 0; i < Math.pow(10, 9); i++) {
   _.values({ a: 1, b: 2, c: 3 });
}

let duration = performance.now() - start;
console.log(duration);

// --------------------
// for...in
// --------------------
function extractValues(obj) {
   const values = [];
   for(var key in obj) { 
       values.push(obj[key]); 
   }
   return values;
}
let start = performance.now();

for (let i = 0; i < Math.pow(10, 9); i++) {
   extractValues({ a: 1, b: 2, c: 3 });
}

let duration = performance.now() - start;
console.log(duration);

Measurethat.net

A quite helpful website to create and run JavaScript benchmarks is the www.measurethat.net, where you can run the above benchmark in your computer and check the results by yourself.

You can find the benchmark here, the results here and a screenshot with the test results below:

Categorized in: