运行时和编译时的区别是什么?


当前回答

这里是对“运行时和编译时的区别?”这个问题的回答的扩展。运行时和编译时开销的差异?

产品的运行时性能通过更快地交付结果来提高其质量。产品的编译时性能通过缩短编辑-编译-调试周期来提高其时效性。然而,运行时性能和编译时性能都是实现及时性质量的次要因素。因此,只有当整体产品质量和时效性得到改善时,才应该考虑运行时和编译时性能的改进。

这里有一个很好的进一步阅读的来源:

其他回答

基本上,如果你的编译器能在“编译时”找出你的意思或一个值是什么,它就能硬编码到运行时代码中。显然,如果你的运行时代码每次都要进行计算,那么它会运行得更慢,所以如果你能在编译时确定一些东西,那就更好了。

Eg.

常数合并:

如果我这样写:

int i = 2;
i += MY_CONSTANT;

编译器可以在编译时执行这个计算,因为它知道2是什么,MY_CONSTANT是什么。因此,每次执行时,它都不必执行计算。

运行时是指在运行程序时发生的事情。

编译时是指在编译程序时发生的事情。

Imagine that you are a boss and you have an assistant and a maid, and you give them a list of tasks to do, the assistant (compile time) will grab this list and make a checkup to see if the tasks are understandable and that you didn't write in any awkward language or syntax, so he understands that you want to assign someone for a Job so he assign him for you and he understand that you want some coffee, so his role is over and the maid (run time)starts to run those tasks so she goes to make you some coffee but in sudden she doesn’t find any coffee to make so she stops making it or she acts differently and make you some tea (when the program acts differently because he found an error).

public class RuntimeVsCompileTime {

    public static void main(String[] args) {
        
        //test(new D()); COMPILETIME ERROR
        /**
         * Compiler knows that B is not an instance of A
         */
        test(new B());
    }
    
    /**
     * compiler has no hint whether the actual type is A, B or C
     * C c = (C)a; will be checked during runtime
     * @param a
     */
    public static void test(A a) {
        C c = (C)a;//RUNTIME ERROR
    }

}

    class A{
    
}

    class B extends A{
    
}

    class C extends A{
    
}

    class D{
    
}

以下是前面类似的问题的答案,运行时错误和编译器错误的区别是什么?

编译/编译时/语法/语义错误:编译或编译时错误是由于键入错误而发生的错误,如果我们没有遵循任何编程语言的正确语法和语义,那么编译器就会抛出编译时错误。除非您删除所有语法错误或调试编译时错误,否则它们不会让您的程序执行一行。 例如:在C语言中缺少分号或将int错误地输入为int。

运行时错误:运行时错误是指程序处于运行状态时产生的错误。这些类型的错误将导致您的程序出乎意料地运行,甚至可能杀死您的程序。它们通常被称为例外。 示例:假设您正在读取一个不存在的文件,将导致运行时错误。

阅读更多关于所有编程错误