js合并字符串的3种方法和效率
/* abc abc abc*/
function concat(s,n)
{
let a = new Array(n);
a.fill(s);
let str = a.join('');
a = null;
return str;
}
function concat1(s, n){
let count = n;
let str = '';
while(count > 0)
{
str += s;
count --;
}
return str;
}
function tco(f) {
var value;
var active = false;
var accumulated = [];
return function accumulator() {
accumulated.push(arguments);
if(!active) {
active = true;
while(accumulated.length) {
value = f.apply(this, accumulated.shift());
}
active = false;
return value;
}
};
}
const concat2 = tco(function ( s,n, ret = '')
{
if(n == 1) return s+ret;
return concat2(s, n-1, ret+s);
})
let n = 10000*100;
let startTime = new Date();
let str = concat('abc',n);
let endTime = new Date();
let str1 = concat1('abc',n);
let endTime1 = new Date();
let str2 = concat2('abc',n);
//console.log('the result is \"' + str2 + '\"');
let endTime2 = new Date();
//console.log('the result is \"' + str + '\"');
console.log('time:' + (endTime.getTime() - startTime.getTime()));
console.log('time1:' + (endTime1.getTime() - endTime.getTime()));
console.log('time2:' + (endTime2.getTime() - endTime1.getTime()));
1. 10000*100
time:135
time1:364
time2:684
2:10000*1000
time:1357
time1:7395
time2:6883
time:1357time1:7395time2:6883