【发布时间】:2014-07-22 17:34:30
【问题描述】:
我从来不知道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。这是我使用this guide 对speed up 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)
【问题讨论】:
-
你看过这个吗?具体而言,“使用严格”如何执行以下“它会禁用令人困惑或考虑不周的功能”。 stackoverflow.com/questions/1335851/…
-
为什么禁用这些功能会使未优化函数的运行时间大大变慢,而优化函数的运行时间却快>10%?
-
我能得出的唯一结论是,strict 必须以某种方式减缓对
arguments的修改,并加速简单的迭代和元素分配......
标签: node.js optimization v8 strict