fork download
  1. import java.util.regex.Pattern;
  2.  
  3. class Test {
  4. private Pattern pattern;
  5. private boolean[] table;
  6.  
  7. public boolean matches1(String a) {
  8. return pattern.matcher(a).matches();
  9. }
  10.  
  11. public boolean matches2(String a) {
  12. int length = a.length();
  13. for (int i = 0; i < length; ++i)
  14. if (!this.table[a.charAt(i)]) return false;
  15. return true;
  16. }
  17.  
  18. public Test() {
  19. String chars = "adhst32pomnbqf51kczyx94";
  20. this.pattern = Pattern.compile(String.format("[%s]*", chars));
  21. this.table = new boolean[256];
  22. for (int i = 0; i < chars.length(); ++i)
  23. this.table[chars.charAt(i)] = true;
  24. }
  25.  
  26. public static void main(String[] args) {
  27. boolean matches;
  28. Test test = new Test();
  29.  
  30. long start;
  31.  
  32. System.out.println("Regex\n=========================");
  33. start = System.currentTimeMillis();
  34. // best case
  35. for (int i = 0; i < 100000; ++i)
  36. if (test.matches1("egijlruvw0678"))
  37. System.out.println("error!");
  38.  
  39. System.out.printf("Time 1: %d\n", (System.currentTimeMillis() - start));
  40. start = System.currentTimeMillis();
  41.  
  42. // worst case
  43. for (int i = 0; i < 1000000; ++i)
  44. if (!test.matches1("st32pomnbqf51kczyx9"))
  45. System.out.println("error!");
  46.  
  47. System.out.printf("Time 2: %d\n", (System.currentTimeMillis() - start));
  48. start = System.currentTimeMillis();
  49.  
  50. // average case
  51. for (int i = 0; i < 1000000; ++i)
  52. if (!test.matches1("st32pomnbq2"))
  53. System.out.println("error!");
  54.  
  55. System.out.printf("Time 3: %d\n", (System.currentTimeMillis() - start));
  56.  
  57. System.out.println("Lookup table\n=========================");
  58. start = System.currentTimeMillis();
  59. // best case
  60. for (int i = 0; i < 100000; ++i)
  61. if (test.matches2("egijlruvw0678"))
  62. System.out.println("error!");
  63.  
  64. System.out.printf("Time 1: %d\n", (System.currentTimeMillis() - start));
  65. start = System.currentTimeMillis();
  66.  
  67. // worst case
  68. for (int i = 0; i < 1000000; ++i)
  69. if (!test.matches2("st32pomnbqf51kczyx9"))
  70. System.out.println("error!");
  71.  
  72. System.out.printf("Time 2: %d\n", (System.currentTimeMillis() - start));
  73. start = System.currentTimeMillis();
  74.  
  75. // average case
  76. for (int i = 0; i < 1000000; ++i)
  77. if (!test.matches2("st32pomnbq2"))
  78. System.out.println("error!");
  79.  
  80. System.out.printf("Time 3: %d\n", (System.currentTimeMillis() - start));
  81. }
  82. }
  83.  
Success #stdin #stdout 2.08s 212864KB
stdin
Standard input is empty
stdout
Regex
=========================
Time 1: 43
Time 2: 985
Time 3: 690
Lookup table
=========================
Time 1: 1
Time 2: 178
Time 3: 115