[英]String.lastIndexOf() is there a difference between a char and a string with a single character?
只是想知道是否有人知道如果在执行以下操作方面存在很大差异,那么他们是否知道他们的头脑:
String wibble = "<blah> blah blah </blah>.... <wibble> blah wibble blah </wibble> some more test here";
int i = wibble.lastIndexOf(">");
int j = wibble.lastIndexOf('>');
意见很好,但数据更好。 我写了一个快速基准:
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);
}
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%,但两个版本的执行速度都非常快,因此它可能永远不会成为代码中的瓶颈。
您实际上可以查看String类的源代码。 似乎lastIndex(char)和lastIndex(String)实际上是分开编写的。 String类也应该有开销。 所以char版本可能会快一点,但我怀疑是否会出现任何显着的性能差异。
在性能方面,可能会略有不同。 对于搜索单个字符,使用char
而不是String
更快或更等。
如果可读性没有差异(如本例所示),最好选择仅搜索char的版本。 lastIndexOf的工作量较少 - 在列表中查找单个元素比查找子列表更容易(这实际上是搜索字符串的行为)。
一个字符串有额外的开销,无论它的长度是多少都需要(除非你有一个真正的智能编译器,无论如何都会将单个字符串文字优化为字符常量:)),所以如果你只搜索单个字符串,你应该更喜欢char版本字符。 这不是一个邪恶的优化,因为它在任何一种方式都是可读的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.