skip to Main Content

To check whether a given input is a number, which of the following approaches are more efficient?

!isNaN(input)

OR using regex,

var regex=/^[0-9]+$/;
(x.match(regex))

P.S I’m ignoring empty string ("") for now which will return true for !isNaN("")

2

Answers


  1. if you SIMPLY want to check whether a given input is a number
    then i think using ‘isNan()’ would suffice
    it works for both integer numbers as well as decimals.
    // emphasis on ‘SIMPLY’

    Login or Signup to reply.
  2. There’s a little impact on performance in both cases unless you want to parse a million strings or so. However here is a little benchmark parsing 1 mio. strings per solution. Could be improved of course. In my case (Chromium on KUbuntu) !isNaN() is faster.

    let t = performance.now();
    for (let i = 0; i < 1000000; i++)
    {
      let input = String(i);
      let output = !isNaN(input);
    }
    console.log("!isNaN() took " + (performance.now() - t));
    
    t = performance.now();
    let regex=/^[0-9]+$/;
    for (let i = 0; i < 1000000; i++)
    {
      let input = String(i);
      let output = input.match(regex);
    }
    console.log("match() took " + (performance.now() - t));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search