Best implementation for an isNumber(string) method

前端 未结 19 2605
感动是毒
感动是毒 2020-12-15 20:04

In my limited experience, I\'ve been on several projects that have had some sort of string utility class with methods to determine if a given string is a number. The idea h

19条回答
  •  醉话见心
    2020-12-15 20:28

    I like code:

    public static boolean isIntegerRegex(String str) {
        return str.matches("^[0-9]+$");
    }
    

    But it will good more when create Pattern before use it:

    public static Pattern patternInteger = Pattern.compile("^[0-9]+$");
    public static boolean isIntegerRegex(String str) {
      return patternInteger.matcher(str).matches();
    }
    

    Apply by test we have result:

    This operation isIntegerParseInt took 1313 ms.
    This operation isIntegerRegex took 1178 ms.
    This operation isIntegerRegexNew took 304 ms.
    

    With:

    public class IsIntegerPerformanceTest {
      private static Pattern pattern = Pattern.compile("^[0-9]+$");
    
        public static boolean isIntegerParseInt(String str) {
        try {
          Integer.parseInt(str);
          return true;
        } catch (NumberFormatException nfe) {
        }
        return false;
      }
    
      public static boolean isIntegerRegexNew(String str) {
        return pattern.matcher(str).matches();
      }
    
      public static boolean isIntegerRegex(String str) {
        return str.matches("^[0-9]+$");
      }
    
        public static void main(String[] args) {
            long starttime, endtime;
        int iterations = 1000000;
        starttime = System.currentTimeMillis();
        for (int i = 0; i < iterations; i++) {
          isIntegerParseInt("123");
          isIntegerParseInt("not an int");
          isIntegerParseInt("-321");
        }
        endtime = System.currentTimeMillis();
        System.out.println("This operation isIntegerParseInt took " + (endtime - starttime) + " ms.");
        starttime = System.currentTimeMillis();
        for (int i = 0; i < iterations; i++) {
          isIntegerRegex("123");
          isIntegerRegex("not an int");
          isIntegerRegex("-321");
        }
        endtime = System.currentTimeMillis();
        System.out.println("This operation took isIntegerRegex " + (endtime - starttime) + " ms.");
        starttime = System.currentTimeMillis();
        for (int i = 0; i < iterations; i++) {
          isIntegerRegexNew("123");
          isIntegerRegexNew("not an int");
          isIntegerRegexNew("-321");
        }
        endtime = System.currentTimeMillis();
        System.out.println("This operation took isIntegerRegexNew " + (endtime - starttime) + " ms.");
      }
    }
    

提交回复
热议问题