运行时和编译时的区别是什么?
当前回答
基本上,如果你的编译器能在“编译时”找出你的意思或一个值是什么,它就能硬编码到运行时代码中。显然,如果你的运行时代码每次都要进行计算,那么它会运行得更慢,所以如果你能在编译时确定一些东西,那就更好了。
Eg.
常数合并:
如果我这样写:
int i = 2;
i += MY_CONSTANT;
编译器可以在编译时执行这个计算,因为它知道2是什么,MY_CONSTANT是什么。因此,每次执行时,它都不必执行计算。
其他回答
编译时和运行时之间的差异就是精明的理论家所说的阶段差异的一个例子。它是最难学习的概念之一,特别是对于没有太多编程语言背景的人来说。要解决这个问题,我发现问一下很有帮助
程序满足哪些不变量? 在这个阶段会出现什么问题? 如果阶段成功,后置条件是什么(我们知道什么)? 输入和输出是什么(如果有的话)?
编译时
The program need not satisfy any invariants. In fact, it needn't be a well-formed program at all. You could feed this HTML to the compiler and watch it barf... What can go wrong at compile time: Syntax errors Typechecking errors (Rarely) compiler crashes If the compiler succeeds, what do we know? The program was well formed---a meaningful program in whatever language. It's possible to start running the program. (The program might fail immediately, but at least we can try.) What are the inputs and outputs? Input was the program being compiled, plus any header files, interfaces, libraries, or other voodoo that it needed to import in order to get compiled. Output is hopefully assembly code or relocatable object code or even an executable program. Or if something goes wrong, output is a bunch of error messages.
运行时
We know nothing about the program's invariants---they are whatever the programmer put in. Run-time invariants are rarely enforced by the compiler alone; it needs help from the programmer. What can go wrong are run-time errors: Division by zero Dereferencing a null pointer Running out of memory Also there can be errors that are detected by the program itself: Trying to open a file that isn't there Trying find a web page and discovering that an alleged URL is not well formed If run-time succeeds, the program finishes (or keeps going) without crashing. Inputs and outputs are entirely up to the programmer. Files, windows on the screen, network packets, jobs sent to the printer, you name it. If the program launches missiles, that's an output, and it happens only at run time :-)
这里是对“运行时和编译时的区别?”这个问题的回答的扩展。运行时和编译时开销的差异?
产品的运行时性能通过更快地交付结果来提高其质量。产品的编译时性能通过缩短编辑-编译-调试周期来提高其时效性。然而,运行时性能和编译时性能都是实现及时性质量的次要因素。因此,只有当整体产品质量和时效性得到改善时,才应该考虑运行时和编译时性能的改进。
这里有一个很好的进一步阅读的来源:
编译时间:您作为开发人员编译代码的时间段。
运行时间:用户运行你的软件的时间段。
你需要更明确的定义吗?
嗯,好吧,运行时是用来描述程序运行时发生的事情。
编译时间用来描述在构建程序(通常由编译器)时发生的事情。
(编辑:以下内容适用于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