这里有一些用于不同选项和执行时间结果的代码(JDK 11):
execution time isHex1: 3670 ms
execution time isHex2: 3294 ms
execution time isHex3: 3946 ms
execution time regex: 31288 ms
测试代码:
public class HexPerformanceTest {
@Test
public void testPerformance() {
int count = 100000000;
char[] chars = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
String regexString = new String(chars);
Predicate<String> isHex1Test = testString -> {
boolean isHex = true;
for (char c: testString.toCharArray()) {
if (!isHex1(c)) {
isHex = false;
break;
}
}
return isHex;
};
Predicate<String> isHex2Test = testString -> {
boolean isHex = true;
for (char c: testString.toCharArray()) {
if (!isHex2(c)) {
isHex = false;
break;
}
}
return isHex;
};
Predicate<String> isHex3Test = testString -> {
boolean isHex = true;
for (char c: testString.toCharArray()) {
if (!isHex3(c)) {
isHex = false;
break;
}
}
return isHex;
};
Pattern pattern = Pattern.compile("^[0-9a-fA-F]+$");
Predicate<String> regexTest = testString -> {
Matcher matcher = pattern.matcher(regexString);
return matcher.matches();
};
System.out.println("execution time isHex1: " + milliseconds(regexString, isHex1Test, count) + " ms");
System.out.println("execution time isHex2: " + milliseconds(regexString, isHex2Test, count) + " ms");
System.out.println("execution time isHex3: " + milliseconds(regexString, isHex3Test, count) + " ms");
System.out.println("execution time regex: " + milliseconds(regexString, regexTest, count) + " ms");
}
private long milliseconds(String testString, Predicate<String> hexTest, int count) {
long start = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
hexTest.test(testString);
}
return System.currentTimeMillis() - start;
}
private boolean isHex1(char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
private boolean isHex2(char c) {
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
return true;
default:
return false;
}
}
private boolean isHex3(char c) {
return (Character.digit(c, 16) != -1);
}
}