我以前不知道
没有顶部的
use strict
可以加速运行时间,但是一个简单的use strict
让我的基准测试速度大大提高,而较慢的则明显变得更慢(慢了两倍以上)。发生了什么?//
// RUN WITH AND WITHOUT THIS
//
"use strict";
var assert = require('assert');
var slice = [].slice;
function thunkify_fast(fn){
assert('function' == typeof fn, 'function required');
return function(){
var args = new Array(arguments.length);
for(var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
var ctx = this;
return function(done){
var called;
args.push(function(){
if (called) return;
called = true;
done.apply(null, arguments);
});
try {
fn.apply(ctx, args);
} catch (err) {
done(err);
}
}
}
};
function thunkify_slow(fn){
assert('function' == typeof fn, 'function required');
return function(){
var args = slice.call(arguments);
var ctx = this;
return function(done){
var called;
args.push(function(){
if (called) return;
called = true;
done.apply(null, arguments);
});
try {
fn.apply(ctx, args);
} catch (err) {
done(err);
}
}
}
};
var fn = function () { };
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
//
// Only one wrapper can be sent through the optimized compiler
//
suite.add( 'thunkify#fast', function () { thunkify_fast(fn)(function(){}) } )
.add( 'thunkify#slow', function () { thunkify_slow(fn)(function(){}) } )
.on('cycle', function(event) { console.log(String(event.target)); })
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
.run();
没有顶部的
"use strict"
,结果与此相同。$ node --allow-natives-syntax test.js
thunkify#fast x 8,511,605 ops/sec ±1.22% (95 runs sampled)
thunkify#slow x 4,579,633 ops/sec ±0.68% (96 runs sampled)
Fastest is thunkify#fast
然而,使用"use strict;"
后,我得到了以下结果:
$ node --allow-natives-syntax test.js
thunkify#fast x 9,372,375 ops/sec ±0.45% (100 runs sampled)
thunkify#slow x 1,483,664 ops/sec ±0.93% (96 runs sampled)
Fastest is thunkify#fast
我正在运行nodejs v0.11.13。这是我正在做的工作的一部分,目的是使用这个指南来加速node-thunkify。有趣的是,bluebird优化指南没有提到use strict;
对性能的有益影响。
如果我更改测试用例为,
var f_fast = thunkify_fast(fn);
var f_slow = thunkify_slow(fn);
suite.add( 'thunkify#fast', function () { f_fast(function(){}) } )
.add( 'thunkify#slow', function () { f_slow(function(){}) } )
.on('cycle', function(event) { console.log(String(event.target)); })
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
.run();
因此,移除了调用 thunkify
,我仍然看到相同的东西。在未经优化的代码中使用严格模式会更慢,在经过优化的代码中会更快。
没有严格模式
thunkify#fast x 18,910,556 ops/sec ±0.61% (100 runs sampled)
thunkify#slow x 5,148,036 ops/sec ±0.40% (100 runs sampled)
"使用严格模式;"
thunkify#fast x 19,485,652 ops/sec ±1.27% (99 runs sampled)
thunkify#slow x 1,608,235 ops/sec ±3.37% (93 runs sampled)
arguments
的修改,并加速简单的迭代和元素赋值... - Evan Carroll