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


当前回答

这里有一个非常简单的答案:

Runtime and compile time are programming terms that refer to different stages of software program development. In order to create a program, a developer first writes source code, which defines how the program will function. Small programs may only contain a few hundred lines of source code, while large programs may contain hundreds of thousands of lines of source code. The source code must be compiled into machine code in order to become and executable program. This compilation process is referred to as compile time.(think of a compiler as a translator)

用户可以打开并运行编译后的程序。当应用程序正在运行时,它被称为运行时。

术语“运行时”和“编译时”经常被程序员用来指代不同类型的错误。编译时错误是一种问题,例如语法错误或缺少文件引用,从而阻止程序成功编译。编译器产生编译时错误,并通常指出源代码的哪一行导致了问题。

如果一个程序的源代码已经被编译成一个可执行程序,那么它在程序运行时可能仍然有错误。例子包括不能工作的特性、意外的程序行为或程序崩溃。这些类型的问题被称为运行时错误,因为它们发生在运行时。

参考

其他回答

编制时间:

在编译时执行的操作在最终程序运行时几乎不会产生任何开销,但在构建程序时可能会产生很大开销。

运行时:

或多或少完全相反。构建时成本小,运行程序时成本大。

从另一边;如果在编译时执行了某些操作,那么它只在您的机器上运行;如果在运行时执行了某些操作,那么它将在用户的机器上运行。

相关性

An example of where this is important would be a unit carrying type. A compile time version (like Boost.Units or my version in D) ends up being just as fast as solving the problem with native floating point code while a run-time version ends up having to pack around information about the units that a value are in and perform checks in them along side every operation. On the other hand, the compile time versions requiter that the units of the values be known at compile time and can't deal with the case where they come from run-time input.

嗯,好吧,运行时是用来描述程序运行时发生的事情。

编译时间用来描述在构建程序(通常由编译器)时发生的事情。

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{
    
}

下面是《JAVA编程入门》的作者Daniel Liang关于编译的一段话:

用高级语言编写的程序称为源程序或源代码。因为计算机不能执行源程序,所以必须将源程序转换成机器代码才能执行。翻译可以使用另一种被称为解释器或编译器的编程工具来完成。”(Daniel Liang,“JAVA编程入门”,p8)。

...他仍在继续……

编译器将整个源代码翻译成一个机器代码文件,然后执行机器代码文件。

当我们输入高级/人类可读的代码时,这在一开始是无用的!它必须被翻译成一个序列的“电子事件”在你的小CPU!实现这一目标的第一步是编译。

简单地说:编译时错误发生在这个阶段,而运行时错误稍后发生。

请记住:仅仅因为一个程序没有错误地编译,并不意味着它将没有错误地运行。

运行时错误将发生在程序生命周期的准备、运行或等待部分,而编译时错误将发生在生命周期的“新”阶段之前。

编译时错误的例子:

语法错误——如果你的代码有歧义,你怎么能把它们编译成机器级指令??你的代码需要100%符合语言的语法规则,否则它不能被编译成工作的机器代码。

运行时错误的例子:

内存不足——例如,在给定特定程度的变量时,调用递归函数可能会导致堆栈溢出!编译器怎么能预料到这一点!?它不能。

这就是编译时错误和运行时错误的区别

我们可以将其分为两大类静态绑定和动态绑定。它取决于何时与相应值绑定。如果引用是在编译时解析的,那么它是静态绑定;如果引用是在运行时解析的,那么它是动态绑定。静态绑定和动态绑定又称早期绑定和后期绑定。有时也称为静态多态和动态多态。

约瑟夫Kulandai‏。