在ruby中我们可以通过""操作符去字符串进行倍增,如"ruby"2则返回"rubyruby"。在javascript中,字符串只能用加号,嘛,乘法也加法演变过来的。我们可以搞一个试试。
String.prototype.times = function(n) {//IE6 530-640 FF3 400~550 IE8 840 ~1110 chrome 600~1000
return (new Array(n+1)).join(this);
};
创建一个n+1的空数组,调用join方法。
String.prototype.times = function(n) {//IE6 570~600 FF3 320~430 chrome 550~900 IE8 422~490
return Array.prototype.join.call({length:n+1}, this);
};
创建一个对象,拥有length属性,然后利用call()方法去调用数组原型的join方法。这样就不用创建数组了。
String.prototype.times = (function(){//IE6 500~600 FF3 322~390 chrome 581~900 IE8 430~500
var join = Array.prototype.join,//利用闭包,每次的结果都非常不稳定,让浏览器无法进行优化
obj = { };
return function(n) {
obj.length = n + 1;
return join.call(obj, this);
}
})();
它先把Array.prototype.join与对象缓存起来,这样每次就不用从Array的原型查找join方法与创建对象。
String.prototype.times = function(n) {//IE6 75~110 FF3 26~31 chrome 49 IE8 110
var s = this, total = [];
while(n > 0) {
if (n % 2 == 1) total[total.length] = s;
if (n == 1) break;
s += s;
n = n>>1;
}
return total.join('');
};
一到三都没有利用CPU的分支缓存( CPU branch caching),再结合位运算符,速度就会提高一个数量级了。
String.prototype.times = function(n) {//IE6 47,FF3 20,chrome 57 IE8 97-107
var s = this, c = n * s.length;
do {
s += s;
} while (n = n>>1)
s = s.substring(0, c);
return s;
};
String.prototype.times = function(n) {//IE6 47 FF3 26~27 chrome 0 IE8 0
var s = this, total = "";
while(n > 0) {
if (n % 2 == 1) total += s;
if (n == 1) break;
s += s;
n = n>>1;
}
return total;
};
String.prototype.times = function(n) {//IE6 31 FF3 18 IE8 0 chrome 0
if( n == 1 ) {
return this;
}
var s= this.times(Math.floor(n/2));
s+= s;
if ( n % 2 ) {
s+= this;
}
return s;
}
String.prototype.times = function(n) {//IE6 125 FF3 37 IE8 94~109 chrome 46
var s = this, total = [];
while(n> 0) {//不要写while(n)虽然当n等于0时也是终止循环,
//但这有个转型过程,把0转换为false,比不上n>0快
if (n & 1) total[total.length] = s;
s += s;
n = n>>1;
}
return total.join('');
};
jion优化反而成为拖累!
String.prototype.times = function(by) { // String multiplication
by = (by >> 0);
var t = (by > 1? this.times(by / 2): '' );
return t + (by % 2? t + this: t);
}