Reuse your objects and functions for maximum speed. This technique will
make any function run ~10% faster. You call your functions a
lot, and it adds up quickly in hot code paths.
$ node benchmarks/createNoCodeFunction.jsTotal time 53133Total iterations 100000000Iteration/s 1882069.5236482036$ node benchmarks/reuseNoCodeFunction.jsTotal time 50617Total iterations 100000000Iteration/s 1975620.838848608
The above benchmark uses fibonacci to simulate a real high-cpu load.
The actual numbers might differ for your use case, but the difference
should not.
var reusify = require('reusify')var fib = require('reusify/benchmarks/fib')var instance = reusify(MyObject)// get an object from the cache,// or creates a new one when cache is emptyvar obj = instance.get()// set the stateobj.num = 100obj.func()// reset the state.// if the state contains any external object// do not use delete operator (it is slow)// prefer set them to nullobj.num = 0// store an object in the cacheinstance.release(obj)function
The above example was intended for synchronous code, let's see async:
var reusify = require('reusify')var instance = reusify(MyObject)for (var i = 0; i < 100; i++) { getData(i, console.log)}function getData (value, cb) { var obj = instance.get() obj.value = value obj.cb = cb obj.run()}function MyObject () { this.next = null this.value
Also note how in the above examples, the code, that consumes an instance of MyObject,
reset the state to initial condition, just before storing it in the cache.
That's needed so that every subsequent request for an instance from the cache,
could get a clean instance.
Why
It is faster because V8 doesn't have to collect all the functions you
create. On a short-lived benchmark, it is as fast as creating the
nested function, but on a longer time frame it creates less
pressure on the garbage collector.
Other examples
If you want to see some complex example, checkout middie and steed.
Acknowledgements
Thanks to Trevor Norris for
getting me down the rabbit hole of performance, and thanks to Mathias
Buss for suggesting me to share this
trick.