检查字符串的最快方法是Java中的字母数字 [英] Fastest way to check a string is alphanumeric in Java
问题描述
检查字符串是否只包含字母数字字符的最快方法是什么。
What is the fastest way to check that a String contains only alphanumeric characters.
我有一些代码会嚼掉很多CPU和我想知道是否会比使用预编译的正则表达式更快捷。
I've got some code that is going to chew up a lot of CPU and I wonder if there is going to be a quicker way than using pre-compiled regular expressions.
更新:这么多的投票,关心说明?不应该使用Stackoverflow来讨论用于实现任务的算法可能更快?
UPDATE: So many down votes, care to explain? Stackoverflow should not be used to discuss which algorithm to use to achieve a task might be faster?
推荐答案
我已经编写了测试验证正确的答案。在运行Java 1.6的四核OSX10.8计算机上进行的测试
I've written the tests that verify the "correct" answer. Tests done on a quad core OSX10.8 machine running Java 1.6
有趣的是,使用正则表达式比手动迭代字符串慢大约5-10倍。此外, isAlphanumeric2()
函数略快于 isAlphanumeric()
。
Interestingly using regular expressions turns out to be about 5-10 times slower than manually iterating over a string. Furthermore the isAlphanumeric2()
function is marginally faster than isAlphanumeric()
.
public class QuickTest extends TestCase {
private final int reps = 1000000;
public void testRegexp() {
for(int i = 0; i < reps; i++)
("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
}
public void testIsAlphanumeric() {
for(int i = 0; i < reps; i++)
isAlphanumeric("ab4r3rgf"+i);
}
public void testIsAlphanumeric2() {
for(int i = 0; i < reps; i++)
isAlphanumeric2("ab4r3rgf"+i);
}
public boolean isAlphanumeric(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (!Character.isDigit(c) && !Character.isLetter(c))
return false;
}
return true;
}
public boolean isAlphanumeric2(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
return false;
}
return true;
}
}
这篇关于检查字符串的最快方法是Java中的字母数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!