javascript - 在 benchmark.js 中使用字符串

标签 javascript benchmark.js

benchmark.js 的示例应用将其性能测试定义为字符串而不是 JavaScript 函数:

https://github.com/bestiejs/benchmark.js/blob/master/example/jsperf/index.html#L250

以这种方式定义性能测试有优势吗?为什么它不只是一个函数?

最佳答案

据我所知,通过一长串的调用,函数代码最终到达函数 in benchmark.js名为 getSource,无论如何都会将其转换为字符串:

/**
 * 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”中完成的,它提供了另一种解释,说明每次调用时钟时从字符串中创建基准函数的动机:

// 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.js 的专家,但我对它的理解是,该库故意希望从原始代码启动基准测试,迫使编译器/解释器运行以前从未见过的代码。这对我来说确实有意义,因为假设的浏览器在加载时卡住五秒钟以优化代码可能具有惊人的性能,但忽略它在基准测试中编译所花费的五秒钟是不公平的。此外,它对原始代码进行了相当多的修改,以控制范围和异常处理;基准测试只需要代码作为字符串,以便正确操作它。

从这个 Angular 来看,将函数作为字符串传递并不是特别重要,但没有理由不这样做 - 无论如何它最终都会作为字符串。

关于javascript - 在 benchmark.js 中使用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13278597/

相关文章:

javascript - 如何显示/读取结果(ops/sec)?

javascript - 如何缩小圈子大小?

javascript - 如何在 benchmark.js 中为每个测试添加设置和拆卸

javascript - 表单提交后保留动态表单字段值

javascript - 单击按钮时显示框阴影的 Div

javascript - 对抛出错误的异步代码和同步代码进行基准测试

javascript - benchmark js 的结果是什么意思?

javascript - 定义循环次数 - Benchmark.js

javascript - 如何排列图像 3x3?

javascript - 为什么解析消息首先出现?