我有一系列有点笨拙的 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
}
这样做的明显缺点是我要多次重新检查某个条件。在这种情况下,它是如此之小,我无法想象它有什么区别,但我的问题是:
- C#、Java 等现代编译器是否可以优化第二个示例以删除重复检查? 在此示例中这很好,但如果条件检查也有副作用,则可能会导致问题。
- 一般来说,哪种方法会受到青睐?
最佳答案
C# 中的 AND 语句会被编译器简化,因此如果 Direction.x <= 0,则 else if 语句中的第二个子句将不会被求值,因此不需要在“direction”的基础上嵌套> 0”。
关于java - 与平面 if 语句相比,嵌套 if 语句是否可以提高性能或具有其他优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27247530/