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


当前回答

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

其他回答

我认为它是错误的,以及什么时候可以发现错误。

编制时间:

string my_value = Console.ReadLine();
int i = my_value;

字符串值不能被赋给int类型的变量,因此编译器在编译时肯定知道这段代码有问题

运行时间:

string my_value = Console.ReadLine();
int i = int.Parse(my_value);

这里的结果取决于ReadLine()返回的字符串。有些值可以解析为int型,有些则不能。这只能在运行时确定

将源代码转换为“屏幕|磁盘|网络”可以(大致)以两种方式发生;称之为编译和解释。

在编译程序中(例如c和fortran):

源代码被输入到另一个程序(通常称为编译器),该程序生成一个可执行程序(或一个错误)。 运行可执行文件(通过双击它,或在命令行上键入它的名称)

在第一步发生的事情被称为在“编译时”发生,在第二步发生的事情被称为在“运行时”发生。

在解释程序中(例如MicroSoft basic(在dos上)和python(我想)):

源代码被输入到另一个程序(通常称为解释器),该程序直接“运行”它。在这里,解释器充当程序和操作系统(或非常简单的计算机中的硬件)之间的中间层。

在这种情况下,编译时和运行时之间的差异很难确定,而且与程序员或用户的关系也小得多。

Java是一种混合,代码被编译成字节码,然后在虚拟机上运行,虚拟机通常是字节码的解释器。

还有一种中间情况,即程序被编译为字节码并立即运行(如在awk或perl中)。

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

Eg.

常数合并:

如果我这样写:

int i = 2;
i += MY_CONSTANT;

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

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

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

对于S.O.来说,这不是一个好问题(这不是一个特定的编程问题),但总的来说,这不是一个坏问题。

如果您认为这是微不足道的:那么读时与编译时的区别是什么呢?什么时候这是一个有用的区别?编译器在运行时可用的语言呢?Guy Steele(不是笨蛋,他)在CLTL2中写了7页关于EVAL-WHEN的内容,CL程序员可以使用它来控制这一点。两句话只能勉强给出一个定义,而定义本身还远远不够解释。

In general, it's a tough problem that language designers have seemed to try to avoid. They often just say "here's a compiler, it does compile-time things; everything after that is run-time, have fun". C is designed to be simple to implement, not the most flexible environment for computation. When you don't have the compiler available at runtime, or the ability to easily control when an expression is evaluated, you tend to end up with hacks in the language to fake common uses of macros, or users come up with Design Patterns to simulate having more powerful constructs. A simple-to-implement language can definitely be a worthwhile goal, but that doesn't mean it's the end-all-be-all of programming language design. (I don't use EVAL-WHEN much, but I can't imagine life without it.)

关于编译时和运行时的问题空间是巨大的,而且在很大程度上仍未被探索。这并不是说S.O.是进行讨论的正确场所,但我鼓励人们进一步探索这一领域,特别是那些对它应该是什么没有先入为主概念的人。这个问题既不简单也不愚蠢,我们至少可以给检察官指出正确的方向。

不幸的是,我不知道任何好的参考资料。CLTL2稍微讲了一下,但对于学习它并不是很好。