gpt4 book ai didi

java - 性能差异 : initialize and override in an if-else block, 还是额外的 "else"?

转载 作者:行者123 更新时间:2023-12-02 02:23:01 24 4
gpt4 key购买 nike

我很好奇以下哪种方法更有效:用默认值初始化变量,并且仅在 if-else block 中需要时才覆盖它,或者在根本没有值的情况下初始化变量并设置if-else block 中的值?

这是前者和后者的示例:

前:

    String weightStatus = "Underweight";

if (bMI > 29.9)
{
weightStatus = "Obese";
}

else if (bMI >= 25.0)
{
weightStatus = "Overweight";
}

else if (bMI >= 18.5)
{
weightStatus = "Healthy Weight";
}

后者:

    String weightStatus;

if (bMI > 29.9)
{
weightStatus = "Obese";
}

else if (bMI >= 25.0)
{
weightStatus = "Overweight";
}

else if (bMI >= 18.5)
{
weightStatus = "Healthy Weight";
}
else
{
weightStatus = "Underweight";
}

差异很小,但我忍不住想知道根据变量赋值的工作原理,哪一个在技术上更快。

最佳答案

如你所知,前一种情况,字节码总是会设置变量,然后根据if/then,它可能会再次重置它。

但这也取决于在运行时传递哪些值,如果它们大部分不在 then 分支中,那么我想这不会有太大区别,但如果它们经常进入 then 分支,然后大部分是双重设置执行。

您可以使用以下内容进行测试:

public class MyTest {

private static double START = 0;
private static double END = 100;
private static double INCREMENT = 0.0001;

@Test
public void testFirst() throws Exception {
long time = System.nanoTime();
for (double bMI = START; bMI < END; bMI += INCREMENT) {
first(bMI);
}
System.out.println("First " + (System.nanoTime() - time));
}

@Test
public void testSecond() throws Exception {
long time = System.nanoTime();
for (double bMI = START; bMI < END; bMI += INCREMENT) {
second(bMI);
}
System.out.println("Second " + (System.nanoTime() - time));
}

private String first(double bMI) {
String weightStatus = "Underweight";
if (bMI > 29.9) {
weightStatus = "Obese";
} else if (bMI >= 25.0) {
weightStatus = "Overweight";
} else if (bMI >= 18.5) {
weightStatus = "Healthy Weight";
}
return weightStatus;
}

private String second(double bMI) {
String weightStatus;
if (bMI > 29.9) {
weightStatus = "Obese";
} else if (bMI >= 25.0) {
weightStatus = "Overweight";
} else if (bMI >= 18.5) {
weightStatus = "Healthy Weight";
} else {
weightStatus = "Underweight";
}
return weightStatus;
}
}

关于java - 性能差异 : initialize and override in an if-else block, 还是额外的 "else"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48217666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com