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

标签 java c# if-statement optimization compilation

我有一系列有点笨拙的 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/

相关文章:

Javascript if 语句——不需要 {} 吗?

c++ - 如果声明无效

java - 如何从 StreamingOutput 读取数据

Java 8 - 按大小改进大量文件的排序时间

c# - 用户在我的程序上积极花费了多少时间?

c# - 格式化数据 GridView 中的日期时间绑定(bind)到绑定(bind)列表

java - 返回 DTO 内的另一个实体或 DTO

java - 从另一个类调用子类方法时出错

c# - IIS AppPool 作为 x64 运行(非托管) - 为什么?

javascript - 如果数字在数字部分中