reusify
重用您的对象和函数以获得最大的速度。这个技巧将 使任何函数运行速度提高10%。你称函数为a 很多,并且它在热门代码路径中很快就会增加。
$ node benchmarks/createNoCodeFunction.js
Total time 53133
Total iterations 100000000
Iteration/s 1882069.5236482036
$ node benchmarks/reuseNoCodeFunction.js
Total time 50617
Total iterations 100000000
Iteration/s 1975620.838848608
上面的基准测试使用fibonacci来模拟真正的高cpu负载。 实际的数字可能会因您的用例而有所不同,但是差异 不应该。
使用Node v6.10.0进行基准测试。
这个库是从 fastparallel。
例子
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 empty
var obj = instance.get()
// set the state
obj.num = 100
obj.func()
// reset the state.
// if the state contains any external object
// do not use delete operator (it is slow)
// prefer set them to null
obj.num = 0
// store an object in the cache
instance.release(obj)
function MyObject () {
// you need to define this property
// so V8 can compile MyObject into an
// hidden class
this.next = null
this.num = 0
var that = this
// this function is never reallocated,
// so it can be optimized by V8
this.func = function () {
if (null) {
// do nothing
} else {
// calculates fibonacci
fib(that.num)
}
}
}
上面的例子是用于同步代码的,让我们看看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 = null
var that = this
this.run = function () {
asyncOperation(that.value, that.handle)
}
this.handle = function (err, result) {
that.cb(err, result)
that.value = null
that.cb = null
instance.release(that)
}
}
还要注意在上面的示例中,代码如何使用的实例 MyObject,
将状态重置为初始条件,然后将其存储在缓存中。
这是必要的,这样以后每次从缓存中请求一个实例,
可以得到一个干净的实例。
为什么
它更快,因为V8不需要收集所有的函数 创造。在一个寿命较短的基准测试中,它的速度与创建 嵌套函数,但在较长的时间范围内,它创建的更少 垃圾收集器的压力。
其他的例子
致谢
多亏了 特雷弗·诺里斯 为 把我带进表演的兔子洞,谢谢 马赛厄斯 巴斯 谢谢你建议我分享这个 技巧。
许可证
麻省理工学院