Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Testing Speed of Adding Commas to a number
var testNumber = 3453453453434
var tests = 10000;
//Test 1
setTimeout(function(){
var time = performance.now()
for(var i = 0; i < tests; i++)
numberAddComma(testNumber)
console.log('Function: ' + (performance.now() - time))
}, 100);
//Test 2
setTimeout(function(){
var time = performance.now()
for(var i = 0; i < tests; i++)
numberAddComma2(testNumber)
console.log('Regular Ex: ' + (performance.now() - time))
}, 500);
//Test 3
setTimeout(function(){
var time = performance.now()
for(var i = 0; i < tests; i++)
numberAddComma3(testNumber)
console.log('To Local String: ' + (performance.now() - time))
}, 1000)
function numberAddComma(theNumber){
var returnNumber = ''
theNumber = theNumber.toString().split('').reverse()
var i = theNumber.length; while(i--){
returnNumber = returnNumber + theNumber[i] + (i !== 0 && i % 3 == 0 ? ',' : '')
}
return returnNumber
}
function numberAddComma2(theNumber){
return theNumber.toString().replace(/\B(?=(\d{3})+\b)/g, ",")
}
function numberAddComma3(theNumber){
Number(theNumber).toLocaleString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment