8

(First of all, I should make clear that compilers and virtual machines (aka) are a completely unknown field for me)

As I understand it, every time a Java/C#/... application is run, a VM is invoked and translates intermediate code (bytecode, CIL, etc) to machine instructions.

But why can't this operation done only once - at install time?

Glorfindel
  • 3,167
deprecated
  • 3,297

4 Answers4

10

In the case of Java, the JVM can do optimizations that cross library boundaries. For example you could inline a method from a library into your own client code. This type of optimization could not be done at compile time, because the library may change before execution. It is entirely possible that your libfoo-1.0 is replaced by libfoo-1.1 without a recompile. If that happens, cross-library inlines done at compile time would become totally invalid.

By doing the optimization solely at runtime, there is no worry that the library changing under you will invalidate optimizations.

6

It can and often is, at least with .NET applications. See Native Image Generator

a tool that improves the performance of managed applications. Ngen.exe creates native images, which are files containing compiled processor-specific machine code, and installs them into the native image cache on the local computer. The runtime can use native images from the cache instead of using the just-in-time (JIT) compiler to compile the original assembly...

gnat
  • 20,543
  • 29
  • 115
  • 306
6

Because this prevents them from using many features. For example, how can the JIT generate new generic instantiations from DLLs loaded at run-time? Those DLLs don't exist at install-time.

DeadMG
  • 36,914
3

To rephrase the question in accordance with the clarification:

Why can't the bytecode be compiled down to native code the first time the program is run?

I see the following problems:

  • Where would the results be stored? You can't assume that the file containing the bytecode is writable; you don't want to bloat a developer's machine by dumping a new .exe to permanent storage each time he runs a test; and if you store the file in temporary storage then it will be lost the next time you reboot, so you haven't gained much.

  • You're trading away a slightly slow startup every time for a very slow startup the first time. Not going to leave a great impression with the client.

  • You're going to have significant trouble with dynamic classloading.

Peter Taylor
  • 4,043