运行时和编译时的区别是什么?
当前回答
我一直认为它与程序处理开销以及它如何影响性能有关,如前所述。一个简单的例子是,在代码中定义对象所需的绝对内存。
一个定义的布尔值占用x个内存,然后在编译后的程序中,不能更改。当程序运行时,它确切地知道为x分配多少内存。
另一方面,如果我只是定义了一个泛型对象类型(即一种未定义的占位符或可能是一个指向一些巨大blob的指针),我的对象所需的实际内存是不知道的,直到程序运行,我分配了一些东西给它,因此它必须评估和内存分配等,然后将在运行时动态处理(更多的运行时开销)。
如何动态处理它取决于语言、编译器、操作系统、你的代码等等。
然而,在这一点上,它实际上取决于您使用运行时和编译时的上下文。
其他回答
基本上,如果你的编译器能在“编译时”找出你的意思或一个值是什么,它就能硬编码到运行时代码中。显然,如果你的运行时代码每次都要进行计算,那么它会运行得更慢,所以如果你能在编译时确定一些东西,那就更好了。
Eg.
常数合并:
如果我这样写:
int i = 2;
i += MY_CONSTANT;
编译器可以在编译时执行这个计算,因为它知道2是什么,MY_CONSTANT是什么。因此,每次执行时,它都不必执行计算。
以下是前面类似的问题的答案,运行时错误和编译器错误的区别是什么?
编译/编译时/语法/语义错误:编译或编译时错误是由于键入错误而发生的错误,如果我们没有遵循任何编程语言的正确语法和语义,那么编译器就会抛出编译时错误。除非您删除所有语法错误或调试编译时错误,否则它们不会让您的程序执行一行。 例如:在C语言中缺少分号或将int错误地输入为int。
运行时错误:运行时错误是指程序处于运行状态时产生的错误。这些类型的错误将导致您的程序出乎意料地运行,甚至可能杀死您的程序。它们通常被称为例外。 示例:假设您正在读取一个不存在的文件,将导致运行时错误。
阅读更多关于所有编程错误
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).
(编辑:以下内容适用于c#和类似的强类型编程语言。我不确定这是否对你有帮助)。
例如,在运行程序之前,编译器(在编译时)将检测到以下错误,并将导致编译错误:
int i = "string"; --> error at compile-time
另一方面,像下面这样的错误不能被编译器检测到。您将在运行时(当程序运行时)收到一个错误/异常。
Hashtable ht = new Hashtable();
ht.Add("key", "string");
// the compiler does not know what is stored in the hashtable
// under the key "key"
int i = (int)ht["key"]; // --> exception at run-time
您可以通过阅读实际代码来理解代码编译结构。运行时结构并不清楚,除非您了解所使用的模式。