gpt4 book ai didi

java - 与平面 if 语句相比,嵌套 if 语句是否可以提高性能或具有其他优势?

转载 作者:太空宇宙 更新时间:2023-11-04 14:20:30 25 4
gpt4 key购买 nike

我有一系列有点笨拙的 if 语句,按照习惯,我像这样嵌套:

// Cannot collide with right
if(direction.x < 0)
{
// Cannot collide with top
if(direction.y < 0)
{
// Check left and bottom
}
// Cannot collide with bottom
else if (direction.y > 0)
{
// Check left and top
}
// Cannot collide with top or bottom
else
{
// Check left only

}
}
// Cannot collide with left
else if (direction.x > 0)
{
// Cannot collide with top
if(direction.y < 0)
{
// Check right and bottom
}
// Cannot collide with bottom
else if (direction.y > 0)
{
// Check right and top
}
// Cannot collide with top or bottom
else
{
// Check right only

}
}

但是我发现它有点难以阅读,并且认为将其作为一组简单的 if 语句更容易理解,有点像 switch:

// Cannot collide with right or top
if(direction.x < 0 && direction.y < 0)
{
// Check left and bottom
}
// Cannot collide with right or bottom
else if(direction.x < 0 && direction.y > 0)
{
// Check left and top
}
// Cannot collide with right, top or bottom
else if(direction.x < 0)
{
// Check left only
}
// Cannot collide with left or top
else if (direction.x > 0 && direction.y < 0)
{
// Check right and bottom
}
// Cannot collide with left or bottom
else if (direction.x > 0 && direction.y > 0)
{
// Check right and top
}
// Cannot collide with left, top or bottom
else
{
// Check right only
}

这样做的明显缺点是我要多次重新检查某个条件。在这种情况下,它是如此之小,我无法想象它有什么区别,但我的问题是:

  1. C#、Java 等现代编译器是否可以优化第二个示例以删除重复检查?在此示例中这很好,但如果条件检查也有副作用,则可能会导致问题。
  2. 一般来说,哪种方法会受到青睐?

最佳答案

C# 中的 AND 语句会被编译器简化,因此如果 Direction.x <= 0,则 else if 语句中的第二个子句将不会被求值,因此不需要在“direction”的基础上嵌套> 0”。

关于java - 与平面 if 语句相比,嵌套 if 语句是否可以提高性能或具有其他优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27247530/

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