这是最快的功能!
为什么更快?
- 不逐字符检查(有 1 个例外)
- 使用 while 并增加 1 个 var(char 计数 var)与 for 循环检查长度并增加 2 个 var(通常是 var i 和一个带有 char 计数的 var)
- 使用更少的变量
- 不使用正则表达式!
- 使用(希望)高度优化的函数
-
所有操作都尽可能组合在一起,避免由于多个操作而导致速度下降
String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};
这是一个更慢且更易读的版本:
String.prototype.timesCharExist = function ( chr ) {
var total = 0, last_location = 0, single_char = ( chr + '' )[0];
while( last_location = this.indexOf( single_char, last_location ) + 1 )
{
total = total + 1;
}
return total;
};
由于计数器、长变量名和误用 1 个变量,这个比较慢。
要使用它,您只需这样做:
'The char "a" only shows up twice'.timesCharExist('a');
编辑:(2013/12/16)
请勿与 Opera 12.16 或更早版本一起使用!它将比正则表达式解决方案多花费近 2.5 倍!
在 chrome 上,对于 1,000,000 个字符,此解决方案需要 14 毫秒到 20 毫秒。
同样数量的正则表达式解决方案需要 11-14 毫秒。
使用函数(String.prototype 之外)大约需要 10-13 毫秒。
这里是使用的代码:
String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};
var x=Array(100001).join('1234567890');
console.time('proto');x.timesCharExist('1');console.timeEnd('proto');
console.time('regex');x.match(/1/g).length;console.timeEnd('regex');
var timesCharExist=function(x,c){var t=0,l=0,c=(c+'')[0];while(l=x.indexOf(c,l)+1)++t;return t;};
console.time('func');timesCharExist(x,'1');console.timeEnd('func');
所有解的结果应该是100,000!
注意:如果您希望此函数计数超过 1 个字符,请将 where is c=(c+'')[0] 更改为 c=c+''