I have a fairly time-critical piece of code in a react app that gets run on all user keystrokes in a form. It has no performance issues in general, but I was looking into optimising it a bit and was a little surprised at the performance differences between for (let k in obj)
and Object.keys(obj).reduce
.
I would think that setting up function call stacks, etc., would be expensive in JS, but the functional version of the following routine blows the procedural one out of the water (by a full order of magnitude!).
Here are the different versions:
Procedural
const generateProps = (fields, source, start) => {
if (!fields) return start
let finish = {...start}
for (let k of Object.keys(fields)) {
const fld = fields[k]
if (fld instanceof Array) {
if (fld.length === 0) continue
// Handle an array of scalars (e.g. phoneNumbers)
if (fld[0].hasOwnProperty('value')) {
let sf = {}
for (let i = 0; i < fld.length; i++) {
sf[i] = fld[i]
}
finish = generateProps(sf, source[k], finish)
// Handle an array of fields (e.g. addresses)
} else {
for (let i = 0; i < fld.length; i++) {
finish = generateProps(fld[i], source[k][i], finish)
}
}
} else {
finish = {
hasError: fields[k].hasError || fields[k].value === '' || finish.hasError,
isEditing: fields[k].editing || finish.isEditing,
unchanged: (!fields[k].isNew && fields[k].value === source[k]) && finish.unchanged,
hasNew: fields[k].isNew || finish.hasNew
}
}
}
return finish
}
Functional
const generateProps = (fields, source, start) => {
if (!fields) return start
const keys = Object.keys(fields)
return keys.reduce((props, k) => {
const fld = fields[k]
if (fld instanceof Array) {
if (fld.length === 0) return props
// Handle an array of scalars (e.g. phoneNumbers)
if (fld[0].hasOwnProperty('value')) return generateProps(fld.reduce((sf, f, i) => {sf[i] = f; return sf}, {}), source[k], props)
// Handle an array of fields (e.g. addresses)
return fld.reduce((subp, f, i) => generateProps(f, source[k][i], subp), props)
}
return {
hasError: fields[k].hasError || fields[k].value === '' || props.hasError,
isEditing: fields[k].editing || props.isEditing,
unchanged: (!fields[k].isNew && fields[k].value === source[k]) && props.unchanged,
hasNew: fields[k].isNew || props.hasNew
}
}, start)
}
And here are the jperf results
As you can see when you run the test, the procedural version is nearly 50% slower than the functional. I would be interested to hear a breakdown as to why there is such a stark difference.