benchmark.js的示例应用程序将其性能测试定义为字符串而不是JavaScript函数:
https://github.com/bestiejs/benchmark.js/blob/master/example/jsperf/index.html#L250
以这种方式定义性能测试是否有优势?为什么它不只是一个函数?
发布于 2012-11-08 07:02:26
据我所知,通过一系列长时间的调用,那里的函数代码最终在一个名为getSource的函数in benchmark.js中结束,它无论如何都会将其转换为字符串:
/**
* Gets the source code of a function.
*
* @private
* @param {Function} fn The function.
* @param {String} altSource A string used when a function's source code is unretrievable.
* @returns {String} The function's source code.
*/
function getSource(fn, altSource) {
var result = altSource;
if (isStringable(fn)) {
result = String(fn);
} else if (support.decompilation) {
// escape the `{` for Firefox 1
result = (/^[^{]+\{([\s\S]*)}\s*$/.exec(fn) || 0)[1];
}
// trim string
result = (result || '').replace(/^\s+|\s+$/g, '');
// detect strings containing only the "use strict" directive
return /^(?:\/\*+[\w|\W]*?\*\/|\/\/.*?[\n\r\u2028\u2029]|\s)*(["'])use strict\1;?$/.test(result)
? ''
: result;
}这是在函数" clock“中完成的,该函数提供了另一种解释,说明了每次调用clock时从字符串中生成基准函数的动机:
// Compile in setup/teardown functions and the test loop.
// Create a new compiled test, instead of using the cached `bench.compiled`,
// to avoid potential engine optimizations enabled over the life of the test.此外,为了控制作用域和异常处理,它对原始代码进行了适当的修改;benchmark只需要将代码作为字符串,以便正确地操作它。
在这个视图中,将函数作为字符串传递并不是特别重要,但没有理由不这样做--它无论如何都会以字符串的形式结束。
发布于 2012-11-08 08:08:21
在这种情况下,以字符串或引用的形式添加函数对测试性能没有影响。
请看下面的benchmark.js#L336和示例。医生说这取决于你。
您可能想看看clock函数:benchmark.js#L2452。您将看到,如果一个函数作为引用传递,它将被转换为字符串。更重要的是,整个测试被创建为一个字符串。
我不知道为什么它是一个更好的解决方案的所有优点,但我想到了以下几点:
我想指出的是,我所指出的所有优点都与运行代码的技术方面无关。如果它是一个字符串,它必须被解释和执行指定的次数。然后检查经过了多少时间,这就是基准测试的结果(基本上)。整个概念是相同的:
var counter = N,
after,
before = performance.now;
while(counter--) {
myFun();
}
after = performance.now;
console.log(after - before);https://stackoverflow.com/questions/13278597
复制相似问题