考虑以下两个代码块, http://ideone.com/3nNdVs
String[] matches = new String[] {"Foo", "Bar"};
long start = System.nanoTime();
for(int i=0; i< 1000000; i++) {
String name = "This String is Foo Bar";
for (String s : matches){
name = name.replace(s, "");
}
}
System.out.println((System.nanoTime() - start)/1000000);
matches = {"Foo", "Bar"}
start = time.time()
for x in xrange(1000000):
name = "This String is Foo Bar"
for s in matches:
name = name.replace(s, "")
print time.time() - start
在尝试对这两者的性能进行基准测试时,我发现用 Java 实现的比 Python 花费的时间大约长 50%。这让我非常震惊,因为我原以为 Python 版本会更慢。
那么第一个问题是,是否有更好或更快的方法来执行这两个功能?
其次,如果不是,为什么 Java 版本比 Python 版本慢?
最佳答案
我发现了 python 更快的原因,这是因为 java 中的 .replace 方法使用每次调用 .replace 时都会编译的正则表达式。
有很多更快的选择,但我发现最方便的是使用 org.apache.commons.lang3.StringUtils 库的 .replaceEach,它使用索引来查找和替换子字符串,我知道它仍然比一次编译的正则表达式。
long start = System.nanoTime();
for(int i=0; i< 1000000; i++) {
String name = "This String is Foo Bar";
name = StringUtils.replaceEach(name, matches, replaces);
}
System.out.println((System.nanoTime() - start)/1000000);
不幸的是,我可以在 ide one 上提供一个链接,因为他们没有 apache commons。
我系统上的这个版本的算法比 .replace 方法快大约 1/4,比 python 快大约 1/2。
如果有人有更快的 python 选项请告诉我
谢谢
关于java - 这些字符串操作在 Java 和 Python 中是否等效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22552714/