与 V8 的性能比较

Performance comparison with V8

我目前正在测试解析行的多个案例。

每一行的格式如下:

"dHdX5jOa7ww9cGsW7jQF=dHdX5jOa7ww9cGsW7jQF=dHdX5jOa7ww9cGsW7jQF=dHdX5jOa7ww9cGsW7jQF"

当然有很多行,我需要提取keyvalue.

由找到的第一个“=”分隔。 键中从来没有“=”字符。

是第一个“=”符号之后的剩余字符串。

所以对于这个例子,结果应该是:

{
  key: "dHdX5jOa7ww9cGsW7jQF",
  value: "dHdX5jOa7ww9cGsW7jQF=dHdX5jOa7ww9cGsW7jQF=dHdX5jOa7ww9cGsW7jQF"
}

从这里我们可以迭代多个解决方案:

// the first one is not very efficient with split splice join method
function first(line) {
  const lineSplit = line.split('='),
        key       = lineSplit[0],
        value     = lineSplit.splice(1, lineSplit.length).join('=');

  return {
    key,
    value
  };
}

// the second one execute only what i want to do
// with built-in String prototype's functions
function optimized(line) {
  const index = line.indexOf("="),
        key   = line.substr(0, index),
        value = line.substr(index + 1, line.length);

  return {
    key,
    value
  };
}

// i tried to code the logic myself
function homemade(line) {
    const len = line.length;
    let value = "", key = "", valued = false;
    for (let i = 0; i < len; ++i) {
        const char = line[i];
        if (valued === false) {
            if (char !== '=') {
                key += char;
            } else {
                valued = true;
            }
        } else {
            value += char;
        }
    }

    return {
        key,
        value
    };
}

// and next recode substr and foreach built-in to implemant the same
// function but with homemade substr&foreach
String.prototype.substr2 = function(from, to){
    let str = "";
    for (let i = from; i < to; ++i) {
        str += this[i];
    }
    return str;
};

String.prototype.indexOf2 = function(occ){
    const len = this.length;
    for (let i = 0; i < len; ++i) {
        if (this[i] === occ) {
            return i;
        }
    }
    return -1;
};

function overload(line) {
  const index = line.indexOf2("="),
        key   = line.substr2(0, index),
        value = line.substr2(index + 1, line.length);

  return {
    key,
    value
  };
}

瞧瞧 jsBench 的结果:

[我正在使用 Google Chrome 版本 59.0.3071.104(官方构建)(64 位)]

您可以使用浏览器查看这些函数的结果in this jsBench

我不明白这是怎么回事。我想那是不可能的,因为我只用原生的 for() 和其他类似的东西编写了我需要的代码...

我的问题是:

为什么内置字符串操作明显更快?

为什么这种重复的字符串连接是无效的?

有替代品吗?

Why the builtin string operations are obviously much faster ?

因为它们经过优化,并且使用了 JavaScript 代码无法使用的内部实现技巧。例如,他们通过一次性构建结果来避免重复的字符串连接。

Why this repeated string concatenation is inefficient ?

因为它创建了许多字符串作为中间结果。

Is there an alternative to it ?

使用内置字符串操作:-)