Oma*_*eji 4 java optimization performance
只是想知道是否有人知道如果在执行以下操作方面存在很大差异,那么他们是否知道他们的头脑:
String wibble = "<blah> blah blah </blah>.... <wibble> blah wibble blah </wibble> some more test here";
int i = wibble.lastIndexOf(">");
int j = wibble.lastIndexOf('>');
Run Code Online (Sandbox Code Playgroud)
Kip*_*Kip 12
意见很好,但数据更好.我写了一个快速基准:
public static void main(String[] args)
{
System.out.println("Starting perfo test");
final long NUM_TESTS = 100000000L;
String wibble = "<blah> blah blah </blah>.... <wibble>"
+ " blah wibble blah </wibble> some more test here";
int x = -1;
Stopwatch sw = new Stopwatch();
System.out.println("--perfo test with " + NUM_TESTS + " iterations--");
sw.start();
for(long i = 0; i < NUM_TESTS; i++)
x = wibble.lastIndexOf(">");
sw.stop();
System.out.println("String first pass: " + sw + " seconds");
sw.start();
for(long i = 0; i < NUM_TESTS; i++)
x = wibble.lastIndexOf('>');
sw.stop();
System.out.println("Char first pass: " + sw + " seconds");
sw.start();
for(long i = 0; i < NUM_TESTS; i++)
x = wibble.lastIndexOf('>');
sw.stop();
System.out.println("Char second pass: " + sw + " seconds");
sw.start();
for(long i = 0; i < NUM_TESTS; i++)
x = wibble.lastIndexOf(">");
sw.stop();
System.out.println("String second pass: " + sw + " seconds");
//Compiler warning said x was never read locally.. this is to
//ensure the compiler doesn't optimize "x" away..
System.out.println(x);
}
Run Code Online (Sandbox Code Playgroud)
Starting perfo test --perfo test with 100000000 iterations-- String first pass: 8.750 seconds Char first pass: 6.500 seconds Char second pass: 6.437 seconds String second pass: 8.610 seconds 63
带有char的版本速度提高了大约25%,但两个版本的执行速度都非常快,因此它可能永远不会成为代码中的瓶颈.