JavaScript 4 ways to judge whether a number and the efficiency of comparison _javascript skills

Source: Internet
Author: User
Tags numeric value

Today we have a comparison of the efficiency of chrome for different numerical methods, and the results are as follows:

Note: A regular expression can only be used to determine whether the content in a string is a pure numeric value and cannot be used to judge whether it is a numeric object. Put here for comparison purposes only.

The code is as follows:

 var ret;
 var o = 1;
 var pattern =/^ (-?\d*.? \d*) $/;
 var tostr = {}.tostring;
 var array = {};
 array["[Object number]"] = "number";
 
 Console.log ("All kinds of judging whether the speed of the numerical comparison!" ")
 
 Console.log (" Method one: Pattern.test (o) ");
 Console.time ("a");
 for (Var i=0;i<10000;i++) {
  ret = pattern.test (o);
 }
 Console.timeend ("a");
 Console.log (ret);

 Console.log ("Method two: O instanceof number");
 Console.time ("second");
 for (Var i=0;i<10000;i++) {
  ret = o instanceof number;
 }
 Console.timeend ("second");
 Console.log (ret);
 
 Console.log ("method Three: O.constructor = = number");
 Console.time ("Thirth");
 for (Var i=0;i<10000;i++) {
  ret = O.constructor = = Array;
 }
 Console.timeend ("Thirth");
 Console.log (ret);

 Console.log ("Method four: Array[tostr.call (o)] = = ' number '");
 Console.time ("forth");
 for (Var i=0;i<10000;i++) {
  ret = Array[tostr.call (o)] = = "number";
 }
 Console.timeend ("forth");
 Console.log (ret);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.