-2

Convert string to any number

Way 1

console.log(+"3")

Way 2

console.log("3" * 1)

Way 3

console.log(~~ "3")

Way 4

console.log(parseInt("3"))
console.log(parseFloat("3"))

All the above results are providing same results. But individually it may give some additional functionalities. But I want to know which one is best for performance?

I think "1"*1 (way-2) is one of the best way to convert string to int. Is it correct? If I am wrong, then please let me know which one is best and why?

Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234

1 Answers1

2

But I want to know which one is best for performance?

Test it yourself

const n = 3
function first (num) {
  return +num
}
function second (num) {
  return num * 1
}
function third (num) {
  return ~~ num
}
function forth (num) {
  return parseInt(num)
}

const count = 10000000
const data = new Array(count).fill(n);

console.time('first')
data.map(first)
console.timeEnd('first')

console.time('second')
data.map(second)
console.timeEnd('second')

console.time('third')
data.map(third)
console.timeEnd('third')

console.time('forth')
data.map(forth)
console.timeEnd('forth')

With random number

function first (num) {
  return +num
}
function second (num) {
  return num * 1
}
function third (num) {
  return ~~ num
}
function forth (num) {
  return parseInt(num)
}

const data = "34 123456789 0 0.1 10 15s 1,000 011 45 4512 459 8348 3418 2342.3 4.5 34134343 341234034 3434 340 3481 3869 38906 4 1 2 45 48 38.3 xx 341,430,341 34 123456789 0 0.1 10 15s 1,000 011 45 4512 459 8348 3 906".split(' ');


console.time('first')
data.map(first)
console.timeEnd('first')

console.time('second')
data.map(second)
console.timeEnd('second')

console.time('third')
data.map(third)
console.timeEnd('third')

console.time('forth')
data.map(forth)
console.timeEnd('forth')
Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69