我承认我的测试方法很粗糙并且可能存在缺陷(此外,我不懂 Java,只学够写这个答案),但我的初步证据证明与@dasblinkenlight 的答案相反。我运行了以下代码:
import java.util.*;
import java.lang.*;
class Main
{
private static void test (String regex, String replace, int repetitions)
{
long startTime = System.currentTimeMillis();
for (int i = 0; i < repetitions; i++)
{
String str = "30-Nov-2012 United Kingdom, 31-Oct-2012 31-Oct-2012 United Arab Emirates, 29-Oct-2012 31-Oct-2012 India, ";
str.replaceAll(regex, replace);
}
long endTime = System.currentTimeMillis();
System.out.println("Execution time: " + Long.toString(endTime - startTime));
}
public static void main (String[] args) throws java.lang.Exception
{
test("(\\d{4})\\s", "$1@", 10000);
test("(?<=\\d{4})\\s", "@", 10000);
test("(\\d{4})\\s", "$1@", 10000);
test("(?<=\\d{4})\\s", "@", 10000);
test("(\\d{4})\\s", "$1@", 10000);
test("(?<=\\d{4})\\s", "@", 10000);
test("(\\d{4})\\s", "$1@", 10000);
test("(?<=\\d{4})\\s", "@", 10000);
}
}
...在这里,http://ideone.com/WkHLMN,输出是:
Execution time: 164
Execution time: 140
Execution time: 96
Execution time: 135
Execution time: 95
Execution time: 133
Execution time: 94
Execution time: 130
忽略第一组案例作为与初始化有关的异常值,其余案例似乎表明后一个表达式,使用积极的后向断言,可能会多做 50% 的工作!我怀疑可能是这种情况,因为在传递了感兴趣的字符之后,反向引用需要返回以检查断言是否为真。