运行时和编译时的区别是什么?
当前回答
编制时间:
在编译时执行的操作在最终程序运行时几乎不会产生任何开销,但在构建程序时可能会产生很大开销。
运行时:
或多或少完全相反。构建时成本小,运行程序时成本大。
从另一边;如果在编译时执行了某些操作,那么它只在您的机器上运行;如果在运行时执行了某些操作,那么它将在用户的机器上运行。
相关性
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.
其他回答
(编辑:以下内容适用于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
例如:在强类型语言中,类型可以在编译时或运行时检查。在编译时,这意味着如果类型不兼容,编译器将报错。在运行时,意味着你可以很好地编译你的程序,但在运行时,它会抛出一个异常。
您可以通过阅读实际代码来理解代码编译结构。运行时结构并不清楚,除非您了解所使用的模式。
我认为它是错误的,以及什么时候可以发现错误。
编制时间:
string my_value = Console.ReadLine();
int i = my_value;
字符串值不能被赋给int类型的变量,因此编译器在编译时肯定知道这段代码有问题
运行时间:
string my_value = Console.ReadLine();
int i = int.Parse(my_value);
这里的结果取决于ReadLine()返回的字符串。有些值可以解析为int型,有些则不能。这只能在运行时确定
我一直认为它与程序处理开销以及它如何影响性能有关,如前所述。一个简单的例子是,在代码中定义对象所需的绝对内存。
一个定义的布尔值占用x个内存,然后在编译后的程序中,不能更改。当程序运行时,它确切地知道为x分配多少内存。
另一方面,如果我只是定义了一个泛型对象类型(即一种未定义的占位符或可能是一个指向一些巨大blob的指针),我的对象所需的实际内存是不知道的,直到程序运行,我分配了一些东西给它,因此它必须评估和内存分配等,然后将在运行时动态处理(更多的运行时开销)。
如何动态处理它取决于语言、编译器、操作系统、你的代码等等。
然而,在这一点上,它实际上取决于您使用运行时和编译时的上下文。