1

我正在用 JavaScript 编写一段代码,它应该替换 JSON obj 中多个字符串中出现的所有字符。

并非所有的字符串都包含特定的字符,我们正在谈论很多字符串。所以我的问题是:在谈论效率时,最好是进行替换还是在字符串中搜索字符,并且只有在找到时才进行替换?

换句话说:

var obj = ["str","str2","tr3","str","tr2","str3","str","s22tr2","str3","st","rtr2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3"];

选项1:

for(var i=0;i<obj.length;i++){
  if(obj[i].indexOf("s")!=-1){
      document.write(obj[i].replace(/s/gi,"*"));
  }
}​

选项2:

for(var i=0;i<obj.length;i++){
    document.write(obj[i].replace(/s/gi,"*"));
}​

想法?

谢谢。

4

1 回答 1

0

它取决于 obj 中元素的数量和每个元素的大小,在大多数情况下,直接替换更快。到目前为止,您提供的样本最快的是“加入和替换”。检查这个非常懒惰的例子:

var obj = ["str","str2","tr3","str","tr2","str3","str","s22tr2","str3","st","rtr2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3"];
var b = obj.join(',');
b +=',' + b; //  * 2
b +=',' + b; //  * 4
b +=',' + b; //  * 8
b +=',' + b; //  * 16
b +=',' + b; //  * 32
b +=',' + b; //  * 64
b +=',' + b; //  * 128
obj = b.split(',');
var t1 = new Date().getTime();

for(var i=0;i<obj.length;i++)
    if(obj[i].indexOf("s")!=-1 || obj[i].indexOf("S")!=-1)
        document.write(obj[i].replace(/s/gi,"*"));
    else
        document.write(obj[i]);
document.write('<br>');

var t2 = new Date().getTime();

for(var i=0;i<obj.length;i++)
    document.write(obj[i].replace(/s/gi,"*"));
document.write('<br>');

var t3 = new Date().getTime();

document.write(obj.join('|').replace(/s/gi,"*").split('|').join('')); // see note
document.write('<br>');

var t4 = new Date().getTime();

alert((t2-t1) + ' vs ' + (t3-t2) + ' vs ' + (t4-t3));

注意:'|' 表示不包含在对象元素中的字符(甚至是标记),有助于避免错误。

挑选。

更新:

在第一次测试中添加了大写字母 S。

值得探索的有趣案例:/s/gi.test vs indexOf

于 2012-06-19T18:03:28.963 回答