我目前正在测试解析线路的多个案例。
每一行的格式如下:
"dHdX5jOa7ww9cGsW7jQF=dHdX5jOa7ww9cGsW7jQF=dHdX5jOa7ww9cGsW7jQF=dHdX5jOa7ww9cGsW7jQF"
当然有很多行,我需要提取键和值。
键由第一个" ="分隔。找到。 从来没有" ="密钥中的字符。
值是第一个" ="之后的其余字符串登录。
因此,对于这个例子,结果应该是:
{
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告诉结果:
[我使用谷歌浏览器版本59.0.3071.104(官方版本)(64位)]
您可以使用浏览器in this jsBench
查看这些功能的结果我不明白发生了什么。我想,这是不可能的,因为我只用原生的for(和其他类似的东西)编写了我需要的代码......
我的问题是:
为什么内置字符串操作显然要快得多?
为什么这个重复的字符串连接是不合适的?
有替代品吗?
答案 0 :(得分:2)
为什么内置字符串操作显然要快得多?
因为它们已经过优化,并且使用了JavaScript代码无法使用的内部实现技巧。例如,它们通过一次性构建结果来避免重复的字符串连接。
为什么重复的字符串连接效率低下?
因为它会创建许多字符串作为中间结果。
有替代品吗?
使用内置字符串操作: - )