为目标数字添加逗号分隔,由 baidu.number.comma 想到的

2011.05.17更新:测试数据还不够广泛,在同事的机器上用IE8测试时出现 baidu.number.comma 比 comma 耗时更少的情况,等有时间了还要进一步测试。


逛博客的时候看到了《JavaScript 散记:Tangram》这篇文章,其中提到了给数字添加逗号分隔符的算法。算法如下:

baidu.number.comma = function (source, length) {
	if (!length || length < 1) {
		length = 3;
	}

	source = String(source).split(".");
	source[0] = source[0].replace(new RegExp('(\\d)(?=(\\d{'+length+'})+$)','ig'),"$1,");
	return source.join(".");
};

其中用到了正则,而正则一向是低效率的,特别是在这种使用 new RegExp() 动态生成的时候更明显。

为了测试一下效率,我写了另一种实现:

function comma(source, length){
	if (!length || length < 1) {
		length = 3;
	}
	source = String(source).split('.');
	source[0] = source[0].split('');
	for (var i=source[0].length - length; i>0; i-=length){
		source[0].splice(i, 0, ',');
	}
	source[0] = source[0].join('');
	return source.join('.');
}

测试代码如下:

function test(func, n, num){
	var timer1 = new Date();
	while(n-->0){
		func(num);
	}
	return new Date()-timer1;
}
console.log(test(baidu.number.comma, 100000, '1234567890.123456789'));
console.log(test(comma, 100000, '1234567890.123456789'));

在4个浏览器中的测试结果如下:

初步结论:在这个算法中使用正则表达式确实要慢一些。
原文地址:https://www.cnblogs.com/dishuostec/p/2047767.html