Java字符串last_java – String.lastIndexOf()char和具有单个字符的字符串之间有区别吗?...

意见很好,但数据更好.我写了一个快速基准:

测试代码

public static void main(String[] args)

{

System.out.println("Starting perfo test");

final long NUM_TESTS = 100000000L;

String wibble = " blah blah .... "

+ " blah wibble blah 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%,但两个版本的执行速度都非常快,因此它可能永远不会成为代码中的瓶颈.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值