javascript - Array filtering and object conversion: what is fastest and what other considerations matter? -


say need transform array object, , filtering in process.

i have 2 approaches, 1 chainable functional methods such .map, .filter , .reduce, , 1 loops on array old school for-loop , mutates object.

functional way:

const output = fields     .filter(field => field.required)     .map(field => field.name)     .reduce((acc, cur, i) => {       acc[cur] = false;       return acc;     }, {}); 

old school for-loop way:

let output2 = {}; (var = 0; < fields.length; i++) {   if (fields[i].required) {     output2[fields[i].name] = false;   } } 

i prefer functional approach think leads better readable code. surprised (and disappointed) learn functional approach consistently slower non-functional, old school for-loop way of transforming. please find the jsbench here.

i figure couple of things matter here:

  1. i idiot , implementations flawed , can optimized.
  2. "jsbench not best way measure performance. tool x, y, z better way measure performance"
  3. "the performance penalty functional approach worth because can use const has other beneficial aspects such (semi-) immutability."

anyone care weigh in?

you can find test array i'm using in jsbench link.

the "filter map reduce" loops 3 times same array. 1 loop faster. reduce on own works fine

    const output = fields     .reduce((acc, cur, i) => {       if(cur.required){         acc[cur.name] = false;       }       return acc;     }, {}); 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -