运行时和编译时的区别是什么?
当前回答
看看这个例子:
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)
比如在编译时检查了某些情况,在运行时检查了某些情况,一旦程序满足所有条件,就会得到输出。 否则,您将得到编译时或运行时错误。
其他回答
编制时间:
在编译时执行的操作在最终程序运行时几乎不会产生任何开销,但在构建程序时可能会产生很大开销。
运行时:
或多或少完全相反。构建时成本小,运行程序时成本大。
从另一边;如果在编译时执行了某些操作,那么它只在您的机器上运行;如果在运行时执行了某些操作,那么它将在用户的机器上运行。
相关性
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
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{
}
运行时和编译时的主要区别是:
如果代码中存在语法错误和类型检查,则抛出编译时错误,而-as运行时:它在执行代码后进行检查。 例如:
Int a = 1 Int b = a/0;
这里的第一行末尾没有分号——在执行操作b时执行程序后,>编译时错误,结果是无限的——>运行时错误。
编译时不会查找代码提供的功能的输出,而运行时则会。
您可以通过阅读实际代码来理解代码编译结构。运行时结构并不清楚,除非您了解所使用的模式。