与条件比较的速度 [英] Speed of if compared to conditional

查看:93
本文介绍了与条件比较的速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有个想法,可以使用条件运算符将某些if块转换为单行.但是,我想知道是否会有速度差异.我运行了以下测试:

I had the idea I would turn some of my if blocks into single lines, using the conditional operator. However, I was wondering if there would be a speed discrepancy. I ran the following test:

static long startTime;
static long elapsedTime;
static String s;
    
public static void main(String[] args) {
    startTime = System.nanoTime();
    s = "";
    for (int i= 0; i < 1000000000; i++) {
        if (s.equals("")) {
            s = "";
        }
    }
    
    elapsedTime = System.nanoTime() - startTime;
    
    System.out.println("Type 1 took this long: " + elapsedTime + " ns");
    
    startTime = System.nanoTime();
    s = "";
    for (int i= 0; i < 1000000000; i++) {
        s = (s.equals("") ? "" : s);
    }
    
    elapsedTime = System.nanoTime() - startTime;
    
    System.out.println("Type 2 took this long: " + elapsedTime + " ns");
}

这是我的结果:

类型1花费了这么长时间:3293937157 ns

Type 1 took this long: 3293937157 ns

类型2花费了很长时间:2856769127 ns

Type 2 took this long: 2856769127 ns

我在这里做错什么了吗?

Am I doing something wrong here?

假设s.equals("")一定是正确的,这是使代码更快的一种可行方法吗?

Assuming s.equals("") necessarily is true, is this a viable way to make your code faster?

推荐答案

其他答案具有有用的相关信息,但是如果第一种形式比第一种形式更有效,则它们都不能解决 real 问题.第二种形式.

The other answers have useful information that is relevant but none of them addresses the real question if the first form is more efficient than the second form.

由于未正确完成此基准测试,因此无法提供可靠的结果:对Java代码进行基准测试的一个重要经验法则"是进行预热.在这种情况下,第一个循环为第二个循环提供了预热.

This benchmarking does not provide reliable results since it's not done properly: one important "rule of thumb" in benchmarking Java code is to provide a warm-up. In this case, the first loop provides a warm-up to the second loop.

此答案提供了微基准测试的其他说明以及一些有用的链接.

This answer provides additional instructions for micro-benchmarking as well as some useful links.

这篇关于与条件比较的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆