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


当前回答

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

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).

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

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)

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

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

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

参考

看看这个例子:

public class Test {

    public static void main(String[] args) {
        int[] x=new int[-5];//compile time no error
        System.out.println(x.length);
    }}

上面的代码编译成功,没有语法错误,完全有效。 但是在运行时,它抛出以下错误。

Exception in thread "main" java.lang.NegativeArraySizeException
    at Test.main(Test.java:5)

比如在编译时检查了某些情况,在运行时检查了某些情况,一旦程序满足所有条件,就会得到输出。 否则,您将得到编译时或运行时错误。

编制时间: 将源代码转换为机器码以使其成为可执行文件所花费的时间称为编译时间。

运行时间: 当应用程序正在运行时,它被称为运行时。

编译时错误是那些语法错误,缺少文件引用错误。 运行时错误发生在源代码被编译成可执行程序之后,并且程序正在运行时。例如程序崩溃、意外的程序行为或功能不工作。

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

编制时间:

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

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

运行时间:

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

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