0
I prefer code that reads easier and is more maintainable over time. In addition, I prefer native solutions where possible because using libraries and importing functions is cumbersome. Developer experience is key. This is why I always advocate Function.prototype.
Itâs even more important in React code because using Function.prototype as an event handlerâs prop means you get a cached value for memoization. If you use () => {}, then each time itâs created, youâre building out a completely new function. This causes many components to re-render unnecessarily. Thatâs why youâd have to wrap () => {}, or really any anonymous function in useCallback.
In addition, if you care about test coverage, each const noop = () => {} you create in another uncovered test case.
The answers of that StackOverflow question tell a story of how Function.prototype is super duper slow.
One even shows actual benchmarking code revealing a 70% slowdown using Function.prototype in most browsers. đČ
Hereâs a slightly modified version of that benchmark:
const performanceTest = (func, iterations) => {
const before = performance.now()
for(let i = 0; i < iterations; i++) {
func()
}
const after = performance.now()
const elapsed = after - before
return `${elapsed.toFixed(6)}ms`
}
const iterations = 10000000 // 10 million
console.info(`${iterations.toLocaleString()} iterations.`)
const timings = {
'() => {}': (
performanceTest(
() => {},
iterations,
)
),
'Function.prototype': (
performanceTest(
Function.prototype,
iterations,
)
),
}
console.info(
JSON.stringify(
timings,
null,
4,
)
);