JavaScript:为什么这个循环的优化让它变慢了?

JavaScript: Why did the optimization for this loop made it slower?

以下函数在数组内递归搜索字符串:

function searchStrings(tree, callback) {
  for (var i = 0; i < tree.length; ++i) {
    if (_.isArray(tree[i]) || _.isObject(tree[i])) {
      searchStrings(tree[i], callback)
    } else {
      tree[i] = callback(tree[i])
    }
  }
}

数组如下所示:

[ 'markdown',
  [ 'header', { level: 1 }, 'Title' ],
  [ 'para', '\'Example\'' ],
  [ 'para', '“Just in vate--hr”' ],
  [ 'hr' ],
  [ 'para', 'this is another and this is another hr' ],
  [ 'para', [ 'em', 'thoer' ], ' thrr nest ', [ 'strong', 'ert' ] ],
  [ 'bulletlist',
    [ 'listitem', 'this is a test' ],
    [ 'listitem', 'another test' ] ] ]

我稍后会用它来替换字符串:

function replaceCharacters(tree, callback) {

  console.time('time')

  for (var i = 1; i < tree.length; ++i) {
    if (tree[i][0] === 'para') {
      searchStrings(tree[i], function(str) {
        if (str.match(/"/g)) {
          str = str
            .replace(/"(?=\b|')/g, '“')
            .replace(/"(?!\b|')/g, '”')
        }

        return str
      })
    }
  }

  console.timeEnd('time')

我添加了 if (str.match(/"/g)) 部分,认为如果循环跳过没有 " 的字符串,代码会 运行 更快,因为 replace 不必 运行 用于所有字符串。但是我错了。 time 有那个 if 语句是 1ms 没有那个 if 语句是 0ms:

alex@alex-K43U:~/node/m2k$ ./m2k10.js test.txt time: 1ms

alex@alex-K43U:~/node/m2k$ ./m2k10.js test.txt time: 0ms

这里发生了什么? if (tree[i][0] === 'para') 也是如此吗?

因为你有字符串。

在您的例子中,字符串与 ifs 中的条件匹配。这样,您就可以进行 "small" 比较和替换。您的优化将改善不需要进行替换的情况。

正确的测试应该是不需要进行任何更改的测试。 我还建议一个 much "larger" 案例。在你的差异中没有告诉你什么,因为它可能有另一个原因(也许一个进程刚刚启动并降低了浏览器优先级等等)。