1. Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

Something you probably didn't know about Java

Discussion in 'Programming & Webmastering' started by Oliver_FF, Jun 1, 2008.

  1. Oliver_FF

    Oliver_FF New Member

    Oct 15, 2006
    544 (0.14/day)
    Thanks Received:
    So when someone is talking about Java what pops into your head?

    Here's what I think people think of:
    1. interpreted language
    2. everyone knows interpreted languages are slow
    3. mobile phone games :eek: - can't be *that* powerful a language

    And yes, interpretation is pretty slow. But Java is not slow.

    Suppose someone is writing some code in C that involves a simple loop (say 1M iterations) and some If statements. Nice and simple, first time go at solving a problem, not very well optimized - seeing if it works. The C compiler has some optimizations it can perform at compile time, and these are turned on - so the resulting .exe has been optimized to a certain level, removing the obviously redundant operations that aren't needed, etc.

    Now suppose the exact same code is used in Java. It is compiled to java byte code and ready to run in the JVM (java virtual machine). At run time, the JVM loads the class, interprets the code (slooooow) and starts running the loop. After the initial interpretation the JVM will compile the byte code down to machine code, which will be rather similar to the output of the C compiler. After the first say 10,000 iterations of this loop, things get interesting. The JVM will take a look at the original byte code (which is close in comparison to the original Java code) and examine it and refactor parts. It won't just remove redundant operations like the C compiler, it will actually change the code layout to improve performance. This is only possible because the original byte code is present for reference. This extra stage of compilation is called "Just In Time" compilation, or JIT.

    So the result? The C program will run with constant speed all the way through. The Java program will start off slow, then pull up with the speed of the C program, then it will overtake if for the long run to the finish. Obviously the speed difference depends on how good/bad the initial code is - if the C code is already heavily optimized by the coder then the performance of the C will be better. For a general quick throw-it-together bit of programming though Java can outperform C.

    Wiki for further reading:

    Oh, and for the record I think the Java API's are pretty awesome
    Bjorn_Of_Iceland says thanks.
    10 Year Member at TPU

Currently Active Users Viewing This Thread: 1 (0 members and 1 guest)