wyc
wyc

Reputation: 55333

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

This following function searches strings recursively inside arrays:

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])
    }
  }
}

The arrays look like this:

[ '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' ] ] ]

Which I'm later using to replace strings:

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')

I added the if (str.match(/"/g)) part thinking that if the loop skips the strings with no " the code would run faster since replace won't have to run for all the strings. But I was wrong. time with that if statement is 1ms and without that if statement is 0ms:

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

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

What's happening here? Is this also true for if (tree[i][0] === 'para') ?

Upvotes: 0

Views: 51

Answers (1)

zozo
zozo

Reputation: 8612

Because you have the string.

In your case, the string matches the condition in the ifs. This way, you do the "small" comparisons AND the replace. Your optimization will improve the cases where no replaces need to be done.

A correct test would be one where no changes need to be done. Also I suggest a much "larger" case. In yours the difference tells you nothing since it can have another reason (maybe a process started just then and lowered browser priority for a bit, etc.).

Upvotes: 1

Related Questions