Slashdot Mirror


Java Performance Urban Legends

An anonymous reader writes "Urban legends are kind of like mind viruses; even though we know they are probably not true, we often can't resist the urge to retell them (and thus infect other gullible "hosts") because they make for such good storytelling. Most urban legends have some basis in fact, which only makes them harder to stamp out. Unfortunately, many pointers and tips about Java performance tuning are a lot like urban legends -- someone, somewhere, passes on a "tip" that has (or had) some basis in fact, but through its continued retelling, has lost what truth it once contained. This article examines some of these urban performance legends and sets the record straight."

90 of 520 comments (clear)

  1. To what extent does this exist in other languages? by Surak · · Score: 5, Interesting

    I wonder to what extent this exists in other languages? For example, there is an oft-cited tip that says using persistent database applications with LAMP applications increases performance. I've found in actual practice that this depends on a lot of factors such as server load, amount of available memory, etc.

    I remember in my Turbo Pascal programming days (heh) that a lot of people said that using Units would degrade performance. So I tried it both ways and it never really made a difference, for my applications anyways.

    I'd say before taking someone's word for it on a performance enhancing technique, test it out. Because not everything you read is true, and not everything you read will apply to every environment or every application.

  2. My favorite Java UL... by ktakki · · Score: 4, Funny

    There was this one guy who worked for Sun Micro and was disappointed at how slowly Java ran on his Sparcstation, so he attached one of those JATO rocket engines...

    k.

    --
    "In spite of everything, I still believe that people are really good at heart." - Anne Frank
  3. Java is Slow by Anonymous Coward · · Score: 4, Funny

    Ok, so none of the things we thought were slow are really slow.

    Then why the hell is it so slow?

    1. Re:Java is slow by etymxris · · Score: 3, Informative
      This is flat out wrong, what is "heavy processing", please describe what causes your machines to run out of memory?
      This is simple. Here are some examples I worked on:
      1. A tax adapter that did operations for each order. Setting a load tester against the server caused the machine to max out on memory. So I eventually had to create my own pool of objects to stop them from getting touched by the garbage collector.
      2. Text parsing/processing that operates on each line of many megabyte files. When done with mutable String objects, it kept increasing memory as a function of time, never reducing the memory load. It's not like I kept references to these objects. I had to reprogram it to not keep allocating objects for each line.
      I'm sure others have their own examples to contribute.
    2. Re:Java is slow by larry+bagina · · Score: 5, Informative

      I think he's talking about something like this:

      while(true)
      {
      Object o = new Object();
      /* snip */
      o = null;
      }

      The GC won't free the memory in realtime (or, sometimes, ever), as would be the case for C++/C with new/delete malloc/free.

      --
      Do you even lift?

      These aren't the 'roids you're looking for.

    3. Re:Java is slow by Curt+Cox · · Score: 2, Informative
      Not to be a pedant, but I doubt either of these were GC bugs.
      1. Your description is a bit too vague, for me to guess with much certainty. I bet you had some finalize methods that were preventing the GC thread from reclaiming your objects fast enough. This situation should be easier to diagnose and prevent than Sun currently makes it, but it isn't really a GC bug. Effective Java has a nice write-up on this problem. If you really think it is a GC bug, try creating a simple test case that demonstrates it. Java has plenty of bugs, but in my experience, trying to construct a simple test case for submission to Bug Parade will often demonstrate that you didn't really understand the problem.
      2. This sounds quite a bit like either this bug, or a close cousin. It is quite nasty, but really a bug in the java.lang.String code, and not in the GC.
    4. Re:Java is Slow by WolfWithoutAClause · · Score: 4, Funny
      Remember the DOS days? Was was GWBASIC so slow? Why were QuickBASIC programs so slow?

      Why, later, was Surak so slow?

      It's because Surak has never written a line of Java in his life and simply trots out the same tired old message that he heard 4 years ago on Slashdot and repeats whenever Java comes up.

      Surak is essentially regurgitating, inspite of JITs and JNIs actually writing pretty good machine code these days.

      Suraks are slow. That's why people try to avoid hiring them.

      --

      -WolfWithoutAClause

      "Gravity is only a theory, not a fact!"
    5. Re:Java is Slow by CyberGarp · · Score: 4, Informative

      I've worked on two embedded projects using Java on low power (energy consumption/CPU performance both) platforms. Both projects had amazingly similar things happen. I stated up from, "Java is interpreted; it will be slower than the C code of the previous project on the platform, potentially significant."

      The reply, "We don't care about performance."

      Four months later... "Why the hell is your code so slow?"

      Interpreted is as interpreted does.

      --

      I used to wonder what was so holy about a silent night, now I have a child.
    6. Re:Java is slow by Curt+Cox · · Score: 2, Interesting
      Unintentionally retained objects can be quite hard to trace and understand in Java. Better tools are definitely needed. I feel yor pain.
      I can't tell the JVM when I'm done with an object, so I have to give it hints, or arrange it so my backlog of garbage doesn't get so big, or simply avoid allocation altogether.
      What do you mean hints? If there are no references to an object, it is eligible for GC. If there are references to an object, it can't be GC'd. What sort of hint do you mean? If you could dispose of an object explicitly, (and consequently without necessarily eliminating all references to it) the language wouldn't be garbage collected.

      When you say "I'm not complaining about the implementation so much as the architecture." are you suggesting GC'd languages make programming harder? If so, let me suggest that the real problem is that Java doesn't have adequate tools for detecting accidentally retained objects.

    7. Re:Java is Slow by CognitivelyDistorted · · Score: 2, Informative
      Java isn't slow. Java programs are slow.

      If you wrote a program with mostly static methods, primitive types, and arrays, minimizing object creation and virtual method calls, it would run almost as fast as the equivalent C++ program. A couple years back, I implemented Sieve of Eratosthenes in C++, Java, and VB, and the speeds were comparable. IIRC, on Windows they were within 10% of each other. On Solaris, bizarrely, C++ kicked Java's ass, but Java was still only about 50% slower.

      But if you write an object-oriented program, it will be slower. OOP tends to be higher-level, and thus faster to write but slower to run. All those memory allocations and virtual method calls take time, and they're difficult to optimize. Also, the standard libraries are kind of slow, because they try to be really general (e.g., synchronized collections).

    8. Re:Java is slow by WolfWithoutAClause · · Score: 4, Informative
      Let's put it this way:

      I've used Java on embedded applications, on systems that create lots, and lots of objects. And I don't recall ever running out of memory, if there wasn't a bug in the Java program.

      But I'm not saying you're lying or wrong, only that a well tuned, well supported, JVM doesn't do this.

      the opportunistic garbage collection of C/C++ simply leads to better performance than any language that tries to do the garbage collection for you.

      What opportunistic garbage collection of C/C++? You mean delete and free? Get real! Personally, I wouldn't trust the average programmer to even collect garbage correctly more than half the time, and that doesn't cut it. I've had way, way less problems with Java GC than I've ever had with C/C++ in a realtime system. People have spent weeks finding memory leaks; and one time a leak I found was a ghastly C++ compiler bug where the compiler screwed up the automatic destructors on unnamed objects.

      --

      -WolfWithoutAClause

      "Gravity is only a theory, not a fact!"
    9. Re:Java is slow by WolfWithoutAClause · · Score: 2, Interesting
      This isn't a valid solution because sometimes your program might actually need that much memory.

      I said you can control the initial size of the memory. Many JVMs will normally not go outside that size unless it has already GCd and it still doesn't have enough memory.

      I should be able to tell the GC that I am done with an object right here and now, rather than waiting for the low priority GC thread to take too long to pick it up.

      Yes, that would certainly be useful; however, you can usually (depending on the VM) kick the GC off at sensible rates or tune the GC to run more often.

      Still, there are alternatives; and I generally still prefer using Java inspite of these kinds of relatively minor shortfalls in the language because it is still a more powerful language than C++ (powerful in the sense of my programs being shorter in Java than C++).

      --

      -WolfWithoutAClause

      "Gravity is only a theory, not a fact!"
    10. Re:Java is Slow by pHDNgell · · Score: 3, Insightful

      That's a dumb benchmark. That will tell you that the program *starts* slow...and that, perhaps, invoking an application for each time you want to do something would be roughly the equivalent of starting a new web browser (IE on Windows doesn't count) every time you want to look at a new web page...or booting your operating system every time you want to run a program.

      People don't generally write one-off small apps they intend to run hundreds of times a day in java. That's not what it's designed to do.

      If you want to compare performance, do something real-like and have it run once in your two or so languages to get a base, and then run them a few thousand times. Something more like this:

      http://www.bagley.org/~doug/shootout/

      --
      -- The world is watching America, and America is watching TV.
    11. Re:Java is slow by etymxris · · Score: 2, Insightful
      Well I wasn't going to reply, since I think I've said everything in my other posts. But since it got moderated up...

      I've used Java on embedded applications, on systems that create lots, and lots of objects. And I don't recall ever running out of memory, if there wasn't a bug in the Java program.
      There is a difference between using up all your memory and running out of memory. Java maxes out the memory that it's allowed to take in the circumstances I was talking about.

      Suppose you have a tight loop that creates a few objects and then disposes of them. Further suppose that loop spikes the CPU, as would be the case for something under constant load or with a lot of data to process. Then you will be creating objects faster than the GC can get rid of them, because the GC is a lower priority than your main thread, which is doing the important stuff. GC is, by its nature, a lower priority task.

      But sometimes it just needs to be higher priority. In the above case, the program will take up all the memory it's allowed. As you suggested elsewhere, you could simply not allow it to take up that much memory. But there might be valid cases where it needs that much memory. In these cases, virtual memory is the sad reality, but correct action is better than no action. However, you do not want all your cases to be this degenerate. So you are forced to decide between simple failure when much memory is needed, or maxing out a large portion of memory in all cases. I shouldn't have to make that choice.

      As others have suggested, I could tweak the GC to deallocate faster. But this is a flaw. Java should make things simpler, not more difficult. Telling the computer when I'm done with an object is a simpler solution (to me, anyway) than having to tweak runtime parameters.

      Personally, I wouldn't trust the average programmer to even collect garbage correctly more than half the time
      If I couldn't trust someone to use new and delete correctly, I wouldn't trust them to do much at all for me. Yes, there are many programmers that mess things up with these operators, but they aren't very good programmers. If you can't use new and delete or free and malloc correctly, then there's probably a lot of other things you can't do well either. Memory management is rather fundamental to computer science.

      Now, the transparent memory access in C++ is certainly dangerous. But I'm not talking about direct access to memory. I'm talking about garbage collection on demand.

      For example, I do not see how things would become much more dangerous in Java if you added a delete operator to complement the new operator. The operator would have the semantics that meant "delete, now". If you tried to access a deleted object, it would throw an exception. The level of danger afforded by such a feature would be vastly outweighed by the advantages wrought.
    12. Re:Java is Slow by Jonner · · Score: 2, Informative

      The slow startup time of typical JVM's does make it feel slow and is a major annoyance. I believe at least part of the problem is that Java was originally designed to be used in a standalone enviornment instead of running on top of a general purpose operating system like *nix or Windows. When the JVM only starts once every few hours, startup time doesn't matter much. Echidna is an attempt to avoid the memory bloat and startup time of many JVM processes. I haven't tried it yet, but I probably will if I do much more with Java.

      More generally, any language or runtime environment that is significantly different from that of the operating system is at a disadvantage. I wonder if any high level, dynamic, or interpreted language might benefit from a server or memory manager for the shared parts of the runtime, instead of each program having its own, independent runtime.

    13. Re:Java is slow by mallorean · · Score: 2, Informative
      Did anyone try running the obvious test....
      public class RunLoop
      {
      public static void main( String[] args )
      {
      while ( true )
      {
      Object o = new Object();
      o = null;
      }
      }
      }
      You can run this till the cows come home and you won't run out of memory. Running the JVM with 64MB and -verbosegc
      ....
      [GC 606K->94K(1984K), 0.0004234 secs]
      .... quizillion times....
      [GC 606K->94K(1984K), 0.0004110 secs]
      ....
      As you can see:
      1. The VM does free memory in "real-time" ( whatever that may mean )
      2. The amortized amount of memory is zero ( it keeps falling back to the base 94K used for the base java classes.
      If you realy want to know how the VMs memory works and how to tune it, you could do worse than read the Hotspot GC Notes. Agreed that Java is not the greatest language there could be, but it is the best mainstream language for a majority of applications. BTW, this test was done on a rather obsolete PIII
      Memory: 127544k/130944k available (1008k kernel code, 412k reserved, 1636k data, 64k init)
      DENTRY hash table entries: 262144 (order: 9, 2097152 bytes)
      Buffer-cache hash table entries: 131072 (order: 7, 524288 bytes)
      Page-cache hash table entries: 32768 (order: 5, 131072 bytes)
      VFS: Diskquotas version dquot_6.4.0 initialized
      CPU: Intel Pentium III (Katmai) stepping 03
    14. Re:Java is slow by dubl-u · · Score: 2, Interesting

      Telling the computer when I'm done with an object is a simpler solution (to me, anyway) than having to tweak runtime parameters.

      Simpler? Sure, if you have just a few objects. But with a lot of objects, it's much, much, much more complicated. As anybody who has spent hours running down a malloc/free error in somebody else's code can tell you.

      If you can't use new and delete or free and malloc correctly, then there's probably a lot of other things you can't do well either.

      Welcome to the human condition.

      I have a limited amount of attention and effort I can spend. The whole point of computers is to take the boring parts and have a machine do them, freeing me to think about the important, interesting parts. For the kind of stuff I code, memory allocation is in the boring category about 99.99% of the time. For the 1 time in 10,000 where it really matters, then fine, I'll write native code. But the rest of the time, let the machines do the donkey work.

      For example, I do not see how things would become much more dangerous in Java if you added a delete operator to complement the new operator.

      You can make the same argument about a lot of things in Java. E.g., multiple inheritance or platform-dependent code. The theory behind Java is that there are some features that a) take an expert to use properly, b) are dangerous when novices try to use them, and c) complicate things a lot when they exist. So Java doesn't allow those, or at least makes it hard enough to get to that only the experts bother (e.g., JNI).

      This sort of daddy-knows-best behavior is annoying, and absent business considerations, I wouldn't put up with it. But if I'm going to have to inherit the code bas of J. Random Programmer, I'd rather it be in Java, because although it's impossible to write really brilliant code, it just can't end up as bad as in C or Perl.

    15. Re:Java is Slow by BenTels0 · · Score: 2, Interesting
      Want to prove it to yourself? Replace 'ls' some day with a Java version of it.

      Actually, I'd be willing to bet you considerable amounts of money (Euro's instead of dollars even, they're currently worth more) that the performance you are perceiving in that test is not Java pur sang but to a far greater extent the load time of the JVM (which, for a job as simple and involved code as limited as for 'ls', is undoubtedly quite significant). The JVM has a nasty tendency, you see, to preload lots of classes -- which, often, don't get used in small programs and so are deadweight. I was playing around with the JNI the other day under JDK1.4.1 on Linux and just wrote a simple "Hello World" -- a C program that embeds the JVM (pretty much what the actual "java" command does), loads a class (two, since the VM must load java.lang.Object in response to my loading my own class), creates an instance, calls a method, ends. Now, I can't claim a perceived performance of "instantaneous" like with a compiled C program, but certainly fast enough that you'd miss it if you blinked. Much faster than the "java" command, which loads a whole slew of stuff.

      Also, as another anekdotal hint towards preloading overhead, I was also playing around recently with java.math.BigInteger and wrote a program that calculates, for input n, the nth Fibonacci number. This is done recursively and it creates a new BigInteger object in each recursive call, plus two to start out with. I also put the "input-calculation" part in a loop, so I have a pretty good idea of performance minus startup overhead. And that, I can assure you, is preceived as instantaneous up until F-number 5500 and "fast" up until 17000-20000 (depends on the person). After that it slacks off until you reach 45065 (where I hit the maximum recursion depth) -- which I assure you will be "slow" pretty much everywhere. By comparison, Mathematica crawls when calculating number 50. And there's no perceived difference with Python, but my Python implementation doesn't do F-numbers beyond 998.

  4. The best tip by Anonymous Coward · · Score: 5, Insightful

    The best tip in the article, which really applies to any language (even to choice of languages), is IMHO
    "Save optimizations for situations where performance improvements are actually needed, and employ optimizations that will make a measurable difference."

  5. Re:Java for Applications.... by Anonymous Coward · · Score: 2, Insightful

    Also, Swing is a bloated pig.

    SWT rules!

  6. Urban MySQL vs. Urban PostgreSQL by philovivero · · Score: 4, Interesting

    Interesting. As a guy who's been a die-hard PostgreSQL for a number of years, and who recently accepted a job doing hardcore MySQL administration, I was dreading it, because everyone knows MySQL has bad transaction management, horrible administration nightmares, and is only good for developers.

    And I'm sure MySQL DBAs all know PostgreSQL is slow, bloated, and is only good for huge database rollouts.

    Except, well. You get the gist. I'm replying to this article because I now know first-hand that both camps are getting a lot of it wrong.

    I've written up what began as a final in-depth studied proof that MySQL wasn't ready for the corporate environment (because I'm a PostgreSQL guy, see?) but ended up reluctantly having to conclude MySQL is slightly more ready for the corporate environment than PostgreSQL!

    The writeup is on a wiki, so feel free to register and add your own experience. Please be ready to back up your opinions with facts.

  7. -1, bloody obvious by Michael's+a+Jerk! · · Score: 2, Funny

    Save optimizations for situations where performance improvements are actually needed, and employ optimizations that will make a measurable difference."

    1) become a journalist
    2) use common sense and lots of bullshit
    3)????
    4) profit!

    The missing step appears to be get an MBA and go into management

    --

    I'm not Seth.

  8. Re:hmmm by Planesdragon · · Score: 5, Funny

    sigh, I can't believe I misspelled it twice

    No, you didn't. You misspelled it once; the second time is simply being consistent.

    Misspelling it twice would be writing "optomizing" and "optomezing"

  9. Antidote by Henry+V+.009 · · Score: 4, Insightful

    One thing to remember is that Java is a 'marketed' language. Hence, be aware of inevitable corporate propaganda. That's not to say that Java is bad, but it is heavily pushed.

    Here's a bit of an antidote: Why Java will always be slower than C++

    1. Re:Antidote by Daleks · · Score: 2, Interesting

      1. All Objects are Allocated on the Heap

      This issue is debatable. The example the author gives is a bad one.

      What small objects? For me these are iterators. I use a lot of them in my designs. Someone else may use complex numbers. A 3D programmer may use a vector or a point class. People dealing with time series data will use a time class. Anybody using these will definitely hate trading a zero-time stack allocation for a constant-time heap allocation. Put that in a loop and that becomes O (n) vs. zero. Add another loop and you get O (n^2) vs. again, zero.

      Don't create a new object each time through the loop. Reuse the object to sidestep allocation/deallocation. In a tight-loop where performance matters this will help. In a situation where performance doesn't matter, then this doesn't matter at all.

      2. Lots of Casts

      Java 1.5 will have generics.

      3. Increased Memory Use

      Well let's look at the three points the author tries to make.

      3.1. Programs that utilize automatic garbage collection typically use about 50% more memory that programs that do manual memory management.

      What's a typical program? This one can be ignored.

      3.2. Many of the objects that would be allocated on stack in C++ will be allocated on the heap in Java.

      See above. This can be minimized.

      3.3 Java objects will be larger, due to all objects having a virtual table plus support for synchronization primitives.

      I'll admit ignorance on this issue, although my gut reaction is that hard facts need to be presented on the issue. As the original article said, Java has come a long way since 1.0.

      4. Lack of Control over Details

      This is a mixed bag. You could say that a language without pointers, and consequently direct memory access, will never be as powerful as a language without. But we know this isn't true. Functional languages are as powerful (from a programmatically expressive point of view, not computationally expressive), if not moreso considering the other features they offer: closures, anonymous functions, first-class functions, etc.

      5. No High-Level Optimizations

      The whole concept of template-metaprogramming is entirely orthogonal to the intended style of C++ programming. Meshing template-metaprogrammed code with regular code is a daunting task (on the large scale). It's a hack to get features that aren't in the language, such as a more computationally inclined macro system, lazy evaluation, etc. With that said, it is useful. However, I would rather see those features actually put into C++ and/or Java rather than having to resort to the abuse of C++'s generic programming facilities. A counter to this could be that templates allow for unbridled extention to C++, but that is most definitely not the case. Until C++ has a macro system that rivals Common Lisp's that assertion cannot be made.

    2. Re:Antidote by WolfWithoutAClause · · Score: 4, Insightful
      My advice is don't follow the link, it's trash. Check this out:

      People dealing with time series data will use a time class. Anybody using these will definitely hate trading a zero-time stack allocation for a constant-time heap allocation. Put that in a loop and that becomes O (n) vs. zero. Add another loop and you get O (n^2) vs. again, zero.

      What? A constant time operation in an 'n' loop is O(n), but then again, the loop is O(n) to start with. Add another loop and you get O(n^2) versus O(n^2). The constant of proportionality has changed, but that's all. If you were using C++, you'd probably call a constructor and possibly destructor anyway; so the difference is not nearly as much as you'd expect; and java heap allocation is only about 3 instructions anyway on a decent VM. This article is total junk.

      --

      -WolfWithoutAClause

      "Gravity is only a theory, not a fact!"
    3. Re:Antidote by Anonymous Coward · · Score: 3, Insightful

      Java will be faster than C++, and very soon (if it isn't already) on the condition that Sun continues to exist for a while.

      Java does virtual method inlining. That, alone, makes it potentially faster than C++. A slightly more intelligent garbage collector designed to decrease page-faults later, and presto, C++ is the slow language.

      [Note that Garbage Collection can't scale very well on multiple CPU machines, so Java still won't be the be-all-and-end-all language unless it divides its objects into seperate "memory pools" a la the Apache Portable Runtime, and GCs them all seperately and scaleably.]

      Even once every test shows that Java is faster - and that is almost certain to happen, because ahead-of-time compilers simply can't compete with runtime-compilers (in principle), people won't stop *using* C++, because they won't believe that Java could ever be fast. But Java is definately the way forward for object-orientated languages.

      You don't have to like OO, of course. And Java will never be as fast as C. But if you like OO, you have to like Java.

      The reason people think Java is slow is generally due to Swing. Swing is just a piss-poor kind of UI framework. If it was compiled with an ahead-of-time compiler, it would just be worse. You shouldn't judge a language by one of its libraries, however.

      (I am not blinded by the holy light of Sun - there are legitamate complaints you could make against Java, usually to do with memory. The article you linked does not invoke any one of them)

      -Emlyn

    4. Re:Antidote by digicosm2 · · Score: 3, Insightful

      errr...

      Saying "Java will always be slower than C++" is like saying that there will always be less graduate students than undergraduates. Java and C++ live in the same Von Neumann-ian world, but C++ is allowed to muck with pointers, and Java isn't. Moreover Java has garbage collection.

      However, I dare say that the time that a programmer saves by not mucking around with pointers is far more valuable than the time saved by typical C++ optimization. This may not hold true in performance-critical domains (like game programming), but for the vast majority of programming problems, it's fine.

      If performance was always critical, why do any of us use Perl or Python? To save time.

    5. Re:Antidote by j3110 · · Score: 4, Insightful

      It's more junk than you even pointed out :)

      My favorite was the cast issue. He fails to recognize that the code he is talking about is run once, then it is a static cast just like most people use in C++. Something that must by dynamically casted at runtime, on the other hand, will be much faster in Java since it doesn't have to figure out the casting for an object every time you cast. It basically does it once, then it will be able to cast any object of the same time to the same casted type as before.

      It's complete idiocy by a person who hasn't spent any significant time using Java.

      If you want to critisize Java you must:

      A: target memory usage, site a specific API and why in your OPINION you don't like it, or target startup time.

      B: have not used C++ techniques of optimization on Java

      C: have tried the latest JVM.

      D: have checked the bug parade, and found that the issue you are talking about is not currently being fixed or has been in the bug parade for a very long time.

      If you don't follow all those, then you are really just taking pot shots at a system that works quite well for a LOT of people. I've never met anyone that didn't like Java after they played with it for a while (except back before 1.3).

      There is a SSH server written in Java now that supports all the features that OpenSSh does... I think I'm going to give it a try... no more CRC buffer overflows for me.

      --
      Karma Clown
    6. Re:Antidote by __past__ · · Score: 2, Insightful
      Saying "Java will always be slower than C++" is like saying that there will always be less graduate students than undergraduates. Java and C++ live in the same Von Neumann-ian world, but C++ is allowed to muck with pointers, and Java isn't. Moreover Java has garbage collection.
      Welcome to the world of optimizing compilers and runtimes! Both things can actually help application performance, because they allow the language implementation to do smart things.

      For example, some implementations of malloc() have quite a noticable overhead, while allocating an object with a generational gc has an overhead of increasing one pointer. Additionally, you get better locality, and the order in which space is reclaimed is better suited for the real usage pattern than what human programmers tend to come up with, to the point that some objects may never be reclaimed, because it just wouldn't pay off enough.

  10. Java is slow by etymxris · · Score: 3, Interesting
    I've programmed in Java before, and love it as a language. Unfortunately, even in the newer iterations of the JVM, you simply cannot trust the virtual machine to get rid of objects efficiently. If you are doing some heavy processing, you simply will exhaust all memory on your machine, even if you explicitly set references to null.

    If there is an "inner loop" of your application that needs performance above all else, and you need to program it in Java for whatever reason, there are two things you should get rid of:
    1. Memory allocations
    2. Function calls
    Of course, if you can do this in C/C++, it will also improve performance, but it is not as critical to be so careful in these lower level languages.

    I've just found that you can't trust the garbage collector, no matter how good people say it is. People have been saying it's great since the beginning of Java, and now they say, "It wasn't good before, but it is now." And they'll be saying the same thing in 3 more years. No matter what, the opportunistic garbage collection of C/C++ simply leads to better performance than any language that tries to do the garbage collection for you.
  11. Ok, so if Java doesn't suck speed wise.. by Large+Green+Mallard · · Score: 2, Funny

    It must be all these Java "programmers" that University CS departments world wide keep churning out that couldn't write a well performing program if their life depended on it?

    *looks at Limewire*

    *looks at administration applets written by Sun which don't work over X11*

  12. jav vm sucks by Anonymous Coward · · Score: 2, Interesting
    Fact: Due to similarities of the MSIL/Java Bytecode, Java bytecode can eb converted into MSIL bytecode. (though not vice versa, due to higher expressiveness of MSIL).

    Fact: Valenz and Leopold did a survey (summarrixed in the most recent issue of Dr Dobbs) whereby Java bytecode programs were converted to MSIL, and the .NET, Rotor, MONO, Sun, Blackdown, etc. VMs were compared. In each case, Microsoft's .NET VM had a 5-20% speed increase over the best java VM, and even the MONO and Rotor VMs had a 2-15% speed increase.

  13. Java vs. RAM by kwerle · · Score: 5, Informative

    has poor start up time, and requires an absolutely massive amount of memory. That, and garbage collection makes almost-real time ("soft" real time I believe is the technical term) UIs more difficult than they should be.

    Oh, good, another one to shoot down. While I don't have any numbers at all, I know that Apple 'fixed' this problem to an extent by making parts of java shared, just like any shlibs. This alleviates the 14 apps, 14 bags of shit problem to some extent.

    Apple then returned the changes to SUN, who rolled them into 1.4.x.

    I wish I had numbers. Sorry.

    1. Re:Java vs. RAM by MonopolyNews · · Score: 3, Funny

      don't you understand... there is a Special Case where it will start something up fast... if it's already been started up... so if you start the app 3 times... you have a 66% startup time improvement! you have to study these things closely. Also, VMs can run as fast as compiled code, after all, they are compiled code, but they just won't run your Java code as fast. I mean, the java code can run just as fast, as long as your JVM is optimizing on the fly based on dynamic code profiling... of course, it won't seem faster because the dynamic profiling and recompiling is expensive, but the original code is running faster!

      --

      Slashdot Journal on Monopoly News
    2. Re:Java vs. RAM by Anonymous Coward · · Score: 3, Informative
      Umm... No. I read about this too. I haven't been able to dig up the old article and I don't remember if it is part of Apple's 1.4 (which was released well after Sun's 1.4, and thus not there), or continuing under Apple development. It isn't in Sun's releases, and maybe not in any other public release (I haven't noticed improvements on my PowerBook).
      Apple has indeed implemented shared memory for system class generation (since 1.3 in fact), but it has yet to be backported to a Solaris/Wintel/Linux official release.

      Some more info available here: http://java.sun.com/features/2002/03/mac.osx.html

    3. Re:Java vs. RAM by kwerle · · Score: 3, Informative

      OK. I've been called on the carpet, so it's time to get my facts straight:

      From http://www.apple.com/java/
      Apple developed an innovative new technology that allows Java code to be shared across multiple applications. This reduces the amount of memory that Java applications normally use. And it fits right into Sun?s Hot Spot VM, allowing Mac OS X to remain compatible with standard Java. In addition, Apple has given this implementation to Sun so the company can deploy it on other platforms. Just one example of how Apple supports standards and shares ideas to benefit all.

      You're right in that I can't find any evidence that SUN has rolled this. My hope would still be that this is will be Java Myth of the future. For now it just sucks not to be an Apple user.

      I don't know about Anm's experience on his PB...

  14. Performance is ok, but memory footprint... by Kjella · · Score: 3, Interesting

    Running Freenet and only freenet

    javaw.exe - Mem usage 70,244K
    java.exe - Mem usage 9,808K

    According to task manager. Granted, now I got 512 to take from but it's still eating up much more memory than anything else.

    Kjella

    --
    Live today, because you never know what tomorrow brings
  15. Re:To what extent does this exist in other languag by w42w42 · · Score: 2, Insightful

    Good advice. People sometimes seem to want to solve the problem before knowing what the problem statement is. While their actions may not degrade performance significantly, they often times do not help.

    I've learned over time that everything is relative. There is no cut and dried right and wrong in a lot of cases, but degrees of both. The real answer depends on your need, and not all needs are the same.

  16. kind of right, and that's a problem by g4dget · · Score: 3, Insightful
    While the article has a number of glaring errors, the general point the author is making is right that in terms of raw computer performance, Java has become quite fast.

    But that's not really a good thing. Sun pushed on the JIT on the theory that that would address performance problems. It didn't. The Perl and Python runtimes are much slower than Java's, but Perl and Python applications generally start up much faster and are considerably more responsive.

    Java is as sluggish as ever, and more bloated than it has ever been. What is really responsible for Java's poor performance for real-world applications is its class loading, memory footprint, and just plain awful library design and implementation.

  17. Re:Java for Applications.... by linhux · · Score: 5, Interesting

    Exactly how does "string require careful attention"? I've seen this statement a couple of times, but only to suspect that many people don't really understand what Java Strings are.

    The first mistake, of course, is that people think that (a == b) == a.equals(b) which is, of course, only true if a and b are constant strings or one have invoked intern() on them.

    The second is to not realize that string concatenation with the "+" operator is a special case and only syntactic sugar for StringBuffer operations. Thus, someone not familiar with Java may accidentally generate huge amount of StringBuffer objects in loops.

    However, both these things are very fundamental Java knowledge and among the first thing you learn when studying Java. It's obvious that you don't start coding serious Java without knowing how try..catch..finally works, and equally obvious that you should the know about the deals with the String class.

  18. Re:Java for Applications.... by BrookHarty · · Score: 4, Interesting

    Really, I cant tell if the java programming language is slow, Synchronization is really slow, Declaring classes or methods final makes them faster or Immutable objects are bad for performance.

    But I can tell you, the that almost every Administration application that runs java, sucks out my soul. Trying to run java applications over X at long distances makes me want to commit suicide. (Lucky theres VNC, so its almost usable...) (I think its a Shared memory problem with the way it works with X windows.)

    Then there is the damn JVM's that each app needs, and how i can have multiple versions loaded, so each application works correctly. Java 1.1/1.2/1.3/1.4 and now 1.5 should take even more disk space. Doesnt seem anything is upgradable in java.

    And lets not forget, about how Java likes to interact with all custom window manager replacements on windows. For some reason the screen flickers every time you run a java app. (Havnt seen any answers, but it messes with lightstep, blackbox, geoshell, and even stardock applications.)

    Humm, and cut/paste sucks, yes you can use key combos, but sometimes in windows, its nice to select all, and copy. (Minor bitch, but still annoying when you have switch ways of doing things...)

    If you cant have command line, and you must have a GUI, for gods sake use a HTML. I now make it a point to go with vendors without Java interfaces, they clearly dont use their own products on a day to day basis.

    BTW, i said java Interfaces, not Java Beans, etc. We have java running on solaris, works fine, other than the memory leaks. Its the Admin applications that use Java that are crap.

  19. Profile your software, don't guess by HidingMyName · · Score: 2, Insightful

    Finding where your software spends most of its time can be hard. Having a tool measure resource/time consumption of the regiouns of source code is critical in finding bottlenecks and improving performance.

  20. Error in title by cperciva · · Score: 3, Funny

    "Java Performance Urban Legends" should read "Java Performance is an Urban Legend".

  21. Bullshit by vlad_petric · · Score: 2, Insightful

    Why ? Because it depends so much on the performance optimizations the JVM employs.
    Let's take them one by one:
    <br>
    <LI> Final methods and classes - when you call a final method from the same class you save a lookup in the virtual method table (there is no doubt about what method is going to be called, as it couldn't have been overwritten in a descendent), and furthermore you can inline that method. On a "stupid" JVM (read: from Sun) you won't see any difference, on an optimized one you will.

    <LI> Synchronization can become a bottleneck on SMP systems, because it implies cache synchronization (exiting a synchronized block
    is a memory barrier) - you clearly aren't going to see it on a single processor. But not using synchronization is just as bad (you should use synchronization with <b>all</b> variables that are shared, because you do want memory barriers for correctness)

    <LI> Immutable objects - this one clearly depends on the garbage collector that you use.
    <p>
    Conclusion: the performance of these tricks depend on two things - your JVM and Amdahl's law (how often are these improvements going to manifest themselves)
    <p>

    --

    The Raven

    1. Re:Bullshit by jareds · · Score: 2, Insightful

      You don't appear to know much about synchronization in Java.

      Take your first example. Synchronized methods obtain locks on the object this (or the Class object in the case of static methods), not on the variable referenced therein. If bar() is called while foo() is executing, bar() will not begin executing until foo() finishes. If this were the only synchronized code in a program, it would not be possible for that program to deadlock. However, Java does not find or break deadlocks.

      Your second example is, as you say, a horrible use of synchronization. However, the correct way to be more fine-grained is to place the println statement in a synchronized block.

      You are correct that using synchronization requires you to make sure your code doesn't deadlock, and to consider the reduction in concurrency. However, that really has little to do with the article. Nobody who seriously complains about Java's performance does so because it is possible to use synchronization improperly. This is a programmer error, not a language issue. The article addresses the myth that Java's implementation of locking is horrendously slow.

  22. Enough about the things Java can never fix. by Anonymous Coward · · Score: 5, Insightful

    I'm all for calling a spade a spade, but you can't have your cake and eat it too.

    JNI is the NATIVE INTERFACE. For those that don't already know, that's the interface to the underlying operating system. If the OS misbehaves, hiccups, or is inconsistent, when did it become JAVA's responsibility to clean up? When somebody decided that JAVA was getting a black eye because OS call foo(bar) was crashing the application, or better yet didn't behave exactly like foo(bar) on every OS that provides the JVM.

    Don't like AWT? Well mabye that's because it's built on top of JNI. Enough said.

    Don't like Swing? Well you'd better like AWT. If you don't want the OS to do your GUI work and you don't want the JVM to do your GUI work, mabye you should just get a dry erase marker. You can draw the boxes you need on the screen provided you use a tissue between display updates.

    String requres no more attention than any other bit of JAVA code. If you create dozens of objects for the sole purpose of garbage collection, you either just learned JAVA, you're unaware of what you're doing, or you don't care.

    And about garbage collection. JAVA's garbage collection may not be your cup of tea, but neither are the memory leaks that are still being cleaned up in systems that lack automatic garbage collection.

    So pick your posion. If JAVA isn't perfect, that dosen't make it horrible. JAVA is a good language by most standards, but be honest by stating that it isn't good by your standards.

    My biggest reason for liking JAVA is that it forces people to stop writing bad C code. Which is exactly what it was designed to do.

    1. Re:Enough about the things Java can never fix. by Paleomacus · · Score: 2, Insightful

      I agree JAVA is good at what it's intended to do. Preventing average programmers from blowing things up.

    2. Re:Enough about the things Java can never fix. by pyrrho · · Score: 2, Interesting

      >My biggest reason for liking JAVA is that it forces people to stop writing bad C code. Which is exactly what it was designed to do.

      this is what I dislike about it. I don't like languages built to force me away from a bad habit, it means I've been forced into (someone else's idea of) the perfect habit. I have yet to find the perfect habit.

      The real solution for bad C/C++ code (I slipped C++ in there on purpose) is to learn what you are doing. If you can't learn the ins and outs of procedural logic than don't create an imperitive language, you still have the the real pitfalls still present, and create a new paradigm altogether at a higher language, like Zope.

      There are good problems that VMs address, but they are niche areas (dynamically distributed code that can benefit by using heterogenous networds, and certain idioms like self modifying code... somehow I don't think the joy of self modifying code is what Java is about, but then, I'm told again and again how Java will be as fast as C++ when the JVM's dynamically recompile and optimize code as it runs... loluck), and not general purpose areas.

      --

      -pyrrho

  23. I assume you know by Anonymous Coward · · Score: 3, Interesting

    that the operating system duplicates the amount of memory reported for each thread in a JAVA program?

    For example, should I have a program that has 8 threads and the whole thing uses 28 mb of memory.
    A process listing shows 8 entries each using 28 mb of memory, when in reality only 28 mb and not 224 mb (8 * 28) of memory is being used.

    Before you blame this one on JAVA too, you might want to know that it's a bug in the concept of process memory reporting (ie. the OS) not JAVA. The OS lists 8 scheduleable programs (the java threads) looking up the amount of memory each has access to (28 mb) without ever hinting that they are all using the same 28 mb.

  24. Bigger synchronization myths by Waffle+Iron · · Score: 4, Insightful
    The "synchronization is slow" myth is a very dangerous one, because it motivates programmers to compromise the thread-safety of their programs to avoid a perceived performance hazard.

    However, the article perpetuates another myth: "Synchronization should be easy. The more things you synchronize, the better off you are."

    My hard experience says otherwise. First off, making multithreaded programs work correctly is very hard. Therefore, multiple threads should be avoided if at all possible. You can avoid a lot of these problems in many cases if you use a function like "select()" in a single-threaded program (which, IIRC, Java unfortunately doesn't support). Even though it looks harder to program, it ends up being easier to debug.

    However, sometimes you just can't avoid threads. IMHO, adding "synchronize" as a language keword and encouraging easy creation of threads was a mistake. That doesn't begin to solve your problems. For example, it does nothing to help you avoid deadlocks. In fact, sprinkling synchronized blocks around your program is a recipe for deadlocks and unexpected timing-dependent buggy behavior.

    If you must use multiple threads, there should be one main thread that runs almost all of the program's logic, and a set of highly constrained, carefully controlled worker threads. These threads should not interact with any other (mutable) data structures in the program. Ideally, there should be at most two synchronization points in the program: a work queue and a results queue. The elements of these queues should package up all of the state needed for a worker thread to solve a piece of a problem or deliver its results.

    With an approach like this that has minimal synchronization, there's no need to add a keyword to the language or put synchronization into many library container classes. And of course, performance is hardly an issue at all when you only synchronize twice per worker thread run.

  25. Re:To what extent does this exist in other languag by Tony-A · · Score: 5, Interesting

    I wonder to what extent this exists in other languages?

    Probably lots. Everywhere.
    As a crude approximation, 90% of the time is due to 10% of the code. Improving the "efficiency" of the 90% of the code that is responsible for only 10% of the time tends to be counter-productive. Of course there are no easy magic rules for how to improve the 10% of the code that is responsible for 90% of the time, or even identify exactly what that 10% really is.
    What does work is to have a sense of how long things should take and find and cure whatever is taking much longer than it should.

  26. Why do poor coders have tunnel vision? by ishmalius · · Score: 5, Insightful
    Each tool for its own purpose! If the best language for the task is Java, then use Java. If the best language for your project is C++, then use C++. If it happens to be Billy Bob's Bug-Free Language which suits the job best, well, then, use that one.

    Yes, if I need speed, I use C, the same as anyone else. If I am writing a Web application, I use Java. That's an area where Java excels. And maybe I'll get lucky enough to be able to code a project in Assembly or Lisp, who knows? Programming does not follow the "jack of all trades, expert at none" theory. General concepts map well across the spectrum.

    I find it discouraging that there are so many programmers who only want to learn as much about their job, as to merely be good enough . Don't they feel any pride, or any desire to excel at something?

    Coders who can only handle one language should be paid minimum wage; that is all they are worth. That is because it is neither the language nor the implementation that is important. It is the knowledge of how to program which will ensure your career and pay your bills.

    1. Re:Why do poor coders have tunnel vision? by BitwizeGHC · · Score: 2, Interesting

      The problem is, for Web applications, other languages (such as Perl, LISP, and perhaps Python) come readily to mind as comparable at least to Java. C++ and its like are verbose and confining in a domain (like Web apps) where agility is paramount. In C++'s case this is somewhat justified since like its ancestor C, C++ is only a step or two above assembly language, and thus can be used to produce VERY tight code. Java, running on a VM, has no such excuse.

      Java offers two main advantages: a beefy class library, and enough of the bondage-and-discipline nature to herd legions of mediocre programmers into typing a lot and doing a lot of important-looking work. Other than that it seems to combine the disadvantages of other languages, producing the old saw "Java: All the power of C++ with the blinding speed of Smalltalk".

      The thing about knowing many languages is that you can evaluate them and choose a better language, even than the conventional default. The idea that programmers should know many languages has been invoked far more often to justify the incumbence of bad languages rather than promote the adoption of good ones.

      --
      N4st0r, trixx0r h0bb1tz0rz! Th3y st0l3 0ur pr3c10uzz!
    2. Re:Why do poor coders have tunnel vision? by pHDNgell · · Score: 3, Informative

      Yes, if I need speed, I use C, the same as anyone else.

      Not me. There are some *fast* functional programming language compilers out there. I've ported some of my log processors from python to OCaml, scheme (for the bigloo compiler) and C. The OCaml and bigloo compiled versions were almost exactly the same speed, and only slightly slower than the C version. The C version took me a *LOT* longer to write due to the difficulty of expressing what I was trying to do in C and making sure it was doing it safely.

      In general, I agree with you, but I make great efforts to avoid C, as I am one of those who believe that C is inappropriate for almost every task for which it's used today (even some of the ones for which I'm using it).

      --
      -- The world is watching America, and America is watching TV.
  27. a lot by Trepidity · · Score: 5, Insightful

    A lot of them are things that actually used to be good advice, but for some reason or another (changes in hardware, compilers, etc.) aren't anymore. For example, it used to be a good idea in C to iterate through arrays by incrementing a pointer and dereferencing it instead of incrementing an index and then using array subscripting -- that way you had one increment per iteration, instead of one increment plus one offset calculation (basically you saved the addition that takes place during the array subscripting). However, on many modern C and C++ compilers in many situations, array subscripting will actually be faster than the pointer-incrementing method, because it's easier for the compiler to perform certain optimizations with. [Reference: Michael J. Scott, Programming Language Pragmatics (Morgan Kaufmann, 2000).]

    There's quite a bit of other stuff like this out there as well.

    1. Re:a lot by Ed+Avis · · Score: 2, Insightful

      The moral of the story is, whenever stating any programming rule, always give the reason for it as well. Then people reading the rule later can also check whether the reason is still valid. This applies to all programming language commandments, not just those targeted at performance. It's amazing the number of shops that have fossilized rules from ten or more years ago, the reasons for which are long gone but which still have to be followed anyway although nobody really knows why.

      --
      -- Ed Avis ed@membled.com
  28. Hardware manufacturers want slow software. by Futurepower(R) · · Score: 2, Funny


    It was somewhat shocking to me, but back in the VAX days I learned that software made by hardware manufacturers is as slow as they can get the customer to accept. That makes customers buy more hardware.

    Following the theme of naming products after food items, Sun's next software product is "Molasses".

    If customers accept Molasses, the next January they will release an upgrade called "Molasses in January". The following product will break the naming tradition: It will be a run-anywhere language called "The check is in the mail". After that, there is "When pigs fly", and "When hell freezes".

    The big question in the computing world is how not to become a dog on some manufacturer's leash. Woof, woof, where do you want me to go today, Bill, Steve, or Scott?

  29. Re:Where are the Java desktop applications? by jasonditz · · Score: 2, Interesting

    Corel actually had a Java version of Word Perfect Office.

    OpenOffice at the very least uses Java within it.

    Hotjava is a functional web browser.

    Java just isn't popular on the desktop, because you never know what crazy JVM version someone's going to have on their system. But there's definately a place for it.

  30. The article is wrong by jdennett · · Score: 4, Informative

    In a real project, using JDK 1.3 on various platforms, we had performance issues. So, we measured speed in various ways, and found three main problems.

    1: Synchronization.

    This is slow. Really slow. And it just gets worse when you're running on dual or quad processor machines. StringBuffer is a major offender; in a lame attempt to save one object allocation, it uses a simple reference counting device which requires synchronization for operations as trivial as appending a character. Writing a simple UnsynchronizedStringBuffer gave a measurable performance boost.

    2: Object creation

    This is the real problem. GC is slow. GC on SMP machines is still really slow in JDK 1.3 -- maybe JDK 1.4 is better, my experience is a little out of date. By rewriting large chunks of code to create fewer objects (often by using arrays of primitives) we made it much faster -- close to twice as fast, if memory serves.

    3: Immutable objects

    Yes, these add to GC, and so are bad for performance. But not such a great evil, so long as you don't overuse them.

    Funny that the article "debunks" these myths without figures, when our thorough measurements showed that the problems are real, and in our case would have killed our chances of meeting performance targets had we not found them and dealt with them.

    Some bigger issues for server-side design: be careful how you use remote calls (such as RMI) and how you use persistence (such as JDO). But the small things, which the article seems to misrepresent, matter too.

    1. Re:The article is wrong by Anonymous Coward · · Score: 2, Insightful

      If you're going to bitch about somebody else not showing numbers, then why would anybody believe you when you don't post any numbers of your own? Especially if 2 out of the 3 things you mention are your own damn fault (using too many immutables and building too many objects). I wouldn't be surprised if you blamed lock contention for your slow programs (your #1)

    2. Re:The article is wrong by jdennett · · Score: 2, Insightful

      Most StringBuffer objects are not used from multiple threads. If you need synchronization, use it. In general you don't.

      In particular, if you use a+b on String objects, the compiler will translate to use of a StringBuffer, even though that StringBuffer is manifestly not accessible from any other thread. I don't know if the JVM will optimize away the synchronization -- if it does, the analysis to allow it to do so is an overhead anyway.

      The problems with StringBuffer are varied:

      1. It is overcomplicated because it uses reference counting to avoid a single object allocation.

      2. It guarantees thread safety even though that is not required for most of its uses.

      3. The thread safety protects the integrity of the StringBuffer, but is not enough for most code that could use a StringBuffer from multiple threads: th e granularity of the locking is too fine. This is the same flaw that lead to the introduction of the unsynchronized collection classes (such as ArrayList to replace most uses of Vector).

      4. It is overkill for the uses the Java compiler makes of it in performing string concatenation, and a performance penalty is paid.

      One other interesting thing to note is that my UnsychronizedStringBuffer did not have a default constructor. This forced developers to specify an estimate for the size of the buffer, and so avoided most reallocations -- another performance win, just by restricting an interface.

  31. Re:Where are the Java desktop applications? by jasonditz · · Score: 3, Interesting

    everything Corel does is a disaster, that doesn't mean it couldn't have worked :) Actually I have a buddy who still uses an old WP Java beta and swears it runs wonderfully now that PCs are fast enough to run it properly.

  32. Java not always slower by AT · · Score: 5, Insightful

    Java is not always slower. Java's interpreted nature is generally seen as a weakness, but it has advantages too. For example, the JIT has profiling data immediately at hand when doing optimization, whereas compiled languages won't. Even in cases where compiled languages do use profile feedback, it may not be representative of the current program usage.

    Try writing a simple recursive Fibonacci number calculator in both C++ and Java. The Java one is faster, when using a JIT enabled JVM. Of course, that is a contrived example, but it shows that just-in-time compiling can be faster.

    1. Re:Java not always slower by vidnet · · Score: 2, Interesting
      He's right!

      I tried the simple and stupid

      int fib(int i) {
      if(i<=2) return 1;
      else return fib(i-1)+fib(i-2);
      }

      without optimization on javac and gcc (the latter was slowed down by it so I figured it wouldn't be fair). Calculating up to 45 on my P3 800MHz took, according to 'time', 1m5.554s. Java used 0m51.807s (and that's including the jvm loading).

      Pretty neat.
      java -Xint (no JIT) is still running though.

  33. Why It's Still Slow, and What to Do by Markus+Registrada · · Score: 5, Informative
    Java has always been naturally slow. Like all traditionally slow languages, heroic measures have been taken to attack the problems, and most of the bottlenecks have been looked into. Bytecodes get compiled to native code, garbage-collectors get increasingly clever. Still the programs are way too slow. Why?

    One of the reasons is that interactions with caches are hard to model, making it hard to know what to do to minimize problems. Caching is, inherently, a deal with the devil: you get speed but lose understanding. Sometimes you lose the speed too. Even when you understand, there's not much you can do. Sometimes complicated stuff is inherently expensive.

    When I say caching, I mean not just CPU caches of RAM, but also RAM caches of (potentially swapped-out) process space. If you allow a naive garbage-collector to operate freely, it will happily consume the entire address space available, typically the sum of available RAM and swap space, before garbage-collecting, so the process will run not from RAM but from swap. When it garbage-collects, too, it has to walk a lot of that memory, and swap it all in.

    Just running "ulimit -d" in the shell where the java (or other GC-language) program runs can help a lot. It will GC a lot more often, but if nothing is swapped out, the GC happens a lot faster, and the program's regular execution doesn't have to touch swapped-out pages. You have to know a lot about the program and the data it uses to guess the right ulimit value, and if you guess wrong the program fails, but a thousand-fold speed improvement earns a lot of forgiveness.

    Did you really believe garbage collection would mean you don't have to know about memory management? It makes memory management harder, because the problem remains but there's less you can do about it. (For trivial programs it doesn't matter. If you only write trivial programs, though, you might as well find some other job.)

    There's a similar effect with the CPU cache and RAM. Ideally you want the program code and the data it operates on all to live in cache, because touching the RAM takes 100 times as long at touching cache. With bytecodes, you have a lot more "cache pressure" -- you have the bytecodes themselves, the just-in-time compiler, and the native code it generates. At the same time, since your memory manager generally can't re-use memory that you just freed, it allocates other memory that, when touched, pushes out something else that was useful (such as program code).

    The result is that no matter how clever the JVM is, there's not much it can do to get the performance of real programs close to optimal, or even within a pleasing fraction of equivalent C++ code. This despite all the toy benchmarks that seem to prove otherwise, and which carefully avoid all these real-world problems.

    Of all the promised features of Java (like Lisp before it and C# after it), we're left with the sole remaining feature, that its virtual machine specifies precisely (or abstracts away) enough details of the runtime environment that the code is more portable than a faster native implementation, and the code might get written faster for the author having avoided thinking about details that affect performance.

    The sole saving grace is that most programs don't have much need to run very fast anyway, or if they do it's hard to prove that they ought to run faster. Most people take what they get without complaining, or without complaining to anybody who cares, or without doing anything to make whoever is responsible uncomfortable enough to have to do anything differently. A whole generation trained to accept programs that crash daily or hourly is thrilled to find a program whose biggest problem is that they suspect it might be sluggish.

  34. Hypocritical by javajosh · · Score: 2, Insightful

    While you can't state that a given idiom will improve performance of a program, you also can't state that a given idom will have no effect, either. In particular, the author claims that making methods final has no effect, but fails to show it. The whole article was marked by the same lack of solid evidence the author was decrying. As far as I'm concerned, these Java idioms are still open to question, and the information content was minimal.

  35. Java 1.4+ *does* have non-blocking IO. by mgrant · · Score: 2, Informative

    You can avoid a lot of these problems in many cases if you use a function like "select()" in a single-threaded program (which, IIRC, Java unfortunately doesn't support).

    The standard java NIO APIs support non-blocking IO (which is what select() is).

  36. Sure I remember... by rmdyer · · Score: 2, Insightful



    I used to be the best damn VB programmer there was until around version 6.0. Well, maybe not the best, but I sure did some cool stuff with VB. I got started years ago with GWBASIC too. IBM made one of the first PC compilers for BASIC called "BASIC Compilers 1.0 and 2.0" This was the pre-mouse era, 1985-87'ish days. For lack of a good editor, I used the GWBASIC interface. When we finally compiled with the 1.0 compiler, the code ran a good bit faster. Then, we got the 2.0 compiler. Oh god how slowly our code ran with 2.0. I don't know what happened with 2.0 but it just didn't cut it. We ended up selling our program compiled with the 1.0 compiler.

    Later, around 1988, we got our hands on the first Microsoft QuickBasic compilers. The compiled code then ran like lightning! We found that the QuickBASIC's used the new P-code interpreter. I used QuickBASIC quite a bit. Later, in the early 90's, I changed to VB around version 2.0. VB was quite nimble for program size and execution speed. But when we got version 4.0, it would compile to native code. This was the best performance I ever got out of VB before I realized...hey, the language just isn't giving me what I wanted...eg...smaller size, and faster speed.

    Actually, I had been programming in C since around 1989. And, the more I used C, the more skilled I got at writing C code. The break point came with VB 6.0. I just couldn't justify using VB anymore as it wasn't a good environment for writing command line system administration programs. I was entering into systems administration/programming as my main job, so my code needed to run fast, lean, and mean.

    When the Java phenomenon hit, I saw clearly from my VB experience that this just wasn't going to be a pretty scene. On the one hand, you had plenty of newbies who really didn't know anything about programming spouting the Java mantra. And, with the Internet, it seemed the entire world was going Java. The two bubbles of Java and the Internet seemed to go hand and hand.

    The state of Java now is pure and simply...just bloat. For example, just download and run Morpheus. The thing is written in Java, and for just a simple application, uses 54 Meg. What the heck, 54 Meg!!!??? And, this C# stuff that Microsoft is producing just isn't any better. A simple C# hello world program uses 11 Meg!

    I just can't use applications that take seconds to minutes to load up, then use up all my memory, then run slow as Christmas. I'm a systems programmer, I write applications that load, do what they need to do as fast as possible, then completely unload and get out of the way. My apps have to run background'ed so they don't interfere with the users. I don't want my memory used for program space, it's supposed to be used for data space!

    You might say that memory, disk, and GHz are cheap now. Well my response is...so are your coding skillz! The one thing I've realized over the years is that the more time you spend programming in these high level languages, the more real experience you lose where you could be coding smaller and more efficiently nearer to the core. I'm trying to say that maybe I wasted a good bit of time in VB when I shouldn't have. The same goes for the Java guys. We had a great programming language called C, and C++ that got pushed to the back-burner because of some people who decided that garbage collection and VM's were a "good thing". Well, maybe they are, but at the expense of expertise in programming? I mean come on, if you can't handle pointers, can you really call yourself a programmer?

    I'm so tired of programming environments that keep people from shooting themselves in the foot, or coddle beginning coders. Programming is a skill and an art. It is a good bit like architectural design. Java and VB just turn things into manufactured housing. Do you "want" to live in a double-wide home, or one that was designed to be functional, strong, and beautiful?

    I suppose I'm being too hard on everyone here. Heck, I still use VB

    1. Re:Sure I remember... by bnenning · · Score: 4, Insightful
      I was entering into systems administration/programming as my main job, so my code needed to run fast, lean, and mean.


      Not all programs have the same requirements. In most cases developer time is much more valuable than CPU time.


      Stay as close to the CPU core as possible, but far enough away to be effective. C and C++ are the only languages that accomplish this role.


      Ridiculous. Most good programming techniques are independent of language. If you can't develop effectively in anything but C or C++, then your "skillz" could use some work.


      Think before you code.


      Yes. Think whether the performance gained by using a low-level language is actually significant, and if so whether it offsets the increased development time and greater risk of uncontrolled failures (e.g. exploitable buffer overruns).


      C is a fine language, and is often necessary. But it's a premature optimization to insist on always using it because of nebulous performance concerns.

      --
      How to solve most of our problems: 1.Lots of nuclear plants. 2.Cure aging.
    2. Re:Sure I remember... by cartman · · Score: 2, Insightful

      The state of Java now is pure and simply...just bloat... A simple C# hello world program uses 11 Meg! ... I'm a systems programmer, I write applications that load, do what they need to do as fast as possible, then completely unload and get out of the way.

      Java is used for writing large-scale backend enterprise applications, not small command-line utilities. Nobody is suggesting it as a replacement for perl. With the programs Java is used for, startup time is irrelevant (since it's only started once) and a 50 meg overhead is insignificant.

      We had a great programming language called C, and C++ that got pushed to the back-burner because of some people who decided that garbage collection and VM's were a "good thing".

      C++ wasn't a "great" programming language, it was a syntactic disaster. C is decent for systems programming but still has its defects.

      Well, maybe they are, but at the expense of expertise in programming? I'm so tired of programming environments that keep people from shooting themselves in the foot, or coddle beginning coders.

      This is one attitude that has to be guarded against. Unfortunately, there is a class of people who wrongly call themselves "real programmers." They try to prove their machismo by purposefully avoiding modern techniques, and by doing things in a primitive and difficult way. These programmers overestimate their skills, because they produce unreadable, unportable, bizarre, buggy code that has marginal or nonexistent performance benefits.

      Manual manipulation of pointers causes a 50% increase in bug count, and that's when they're being used by experienced C programmers. When C programmers can write large-scale applications that have no pointer bugs at all, right from the start, then I'll favor letting the "real" programmers have free reign.

      I mean come on, if you can't handle pointers, can you really call yourself a programmer?

      Programming exists to accomplish real-world tasks while meeting abstract design criteria, like code readability. It doesn't exist to dereference pointers, twiddle bits, or shift things around in Unions.

    3. Re:Sure I remember... by BenTels0 · · Score: 2, Insightful

      Great. Another "back-in-my-day" ranter....

      The state of Java now is pure and simply...just bloat.

      Since you indicate yourself that you believe only in the Holy Grail of C and C++ and will not touch anything else, I am going to suggest to you that you are not in any real position to judge.

      You might say that memory, disk, and GHz are cheap now.

      Rather, I'd say that the demands to which you code are no more universal than your insights into the absolute and relative value of Java (or any other language).

      Well my response is...so are your coding skillz!

      I have my opinion of people who deliberately replace "s"es with "z"s and think this says good things about them. As for your skills, if you truly think that coding in C is the only way to write "fast" programs and that everybody who does not code in C must by consequence be a poor developer, I am already underwhelmed. Even without having seen any of your work. And I assure you that your standing as a programmer from the stone age does nothing to alleviate this.

      The one thing I've realized over the years is that the more time you spend programming in these high level languages, the more real experience you lose where you could be coding smaller and more efficiently nearer to the core.

      Your "experience" is fa from universal, I assure you. What you are seeing is a lack of experience and possibly the adverse effects of what passes for computing science education in a lot of places -- it is not related absolutely to the use of any particular language per se, nor does the use of any particular language in and of itself mean that you cannot learn that which you consider to be "hardcore" programming (for what that's worth). Much though I appreciate Edsger Dijkstra's wit, the assertion that using any particular language must necessarily taint a person forever is nonsense.

      Well, maybe they are, but at the expense of expertise in programming?

      Don't confuse "expertise in programming" with "expertise in one particular language". The best programs arise from competent design and following implementation in a language, not from design towards a specific language from the beginning.

      I mean come on, if you can't handle pointers, can you really call yourself a programmer?

      There's an unofficial motto at the CS department at my alma mater: "the best CS engineers are made from those people who come here never having seen a computer in their entire lives". Being a "programmer" doesn't live in having a reflex that causes you to combine the Shift-key and the 8-key, but in being able to grasp the concepts and apply them to the situation you find.

      Programming is a skill and an art. It is a good bit like architectural design.

      The first of those statements is true (and that is an enormously bad thing, make no mistake), the second is patently not. If architecture was like programming, we'd clap all architects in jail because their buildings would collapse so often. Programming is indeed an art -- there are so few people who do it well. Programming on the other hand is nowhere near mature enough to be called anything as well-founded and scientifically based as architecture. We have nowhere near the level of sophistication and scientific backing, let alone the level of reliable education that supports architecture, to pat ourselves on the back to that extent.

      Do you "want" to live in a double-wide home, or one that was designed to be functional, strong, and beautiful?

      The latter. Thank god I need not rely on a programmer to build it for me.

  37. Thread synchronization by morissm · · Score: 3, Interesting

    Hmmm... while I understand what the author is trying to say, I believe his article is misguiding. The problems he mentions are not urban legends and could conceivably be at the root of a performance bottleneck.

    What I think the author is trying to say is that "Premature optimization is the root of all evil in programming". Most of the stuff enumerated in the article usually has a minor impact on performance and no programmer should worry about them during coding.

    However, when all the coding is over, the system will have to meet some performance criteria. If it crawls like a quadraplegic snail, a programmer will have to get its hands dirty and tweak his code to remove the bottlenecks.

    It is very possible that one of those bottlenecks will be rooted in these so-called "urban legends". Gross over-allocation of immutable objects and synchronized methods may impact performance.

    It happened to me a while ago. I was working on a system that was designed to use lots of threads and message passing. We had completed the development and were ready to move on to testing. The system worked pretty well on the developers' workstations (1 CPU) but when we deployed it on our much more powerful servers, the throughput went down. At first, we thought that it was a thread contention problem but after some testing, we realized that the cost of obtaining a lock on multiprocessor systems is orders of magnitude higher than on uniprocessor systems.

    This is because on uniprocessor machines, thread synchronization simply amounts to doing an atomic if/set. However, on multiprocessor machines, complex mechanisms have to be used so that the lock becomes effective for both processors. It involves a lot more overhead because the required extra-cpu operations cost a lot of cycles.

  38. Insignificant optimizations by PizzaFace · · Score: 2, Interesting
    I remember in my Turbo Pascal programming days (heh) that a lot of people said that using Units would degrade performance. So I tried it both ways and it never really made a difference, for my applications anyways.
    That's a good example of optimization tip that is "true" yet useless. Turbo Pascal used a 64K code segment for each unit, so function calls within the main program were "near" calls and function calls to another unit were "far" calls. Each far call made the code one byte bigger than each near call, and used an extra two bytes of stack space while the call was active. (Rubenking, Turbo Pascal 6.0 Techniques and Utilities.) The processor also had to save the CS register before a far call, then restore it afterward, but the performance difference would probably be measured in millionths of a second - possibly measurable in a big tight loop, but certainly not noticeable in a program that did any useful work.

    I don't put much stock in performance tips that are offered without explanation. And in deciding whether to use a tip, I weigh not only the performance trade-offs (near call vs. far call) but also the programming trade-offs (single source file vs. modular code). End-users want reliable functionality, and efficient programming practices often make more difference than code tweaks.
  39. Re:To what extent does this exist in other languag by johannesg · · Score: 2, Informative
    Actually that easy magic _does_ exist: it's the profiler. I don't know if Java has a profiler, but if it has you should find out how to use it because it is incredibly useful for identifying that small portion that needs more attention (*).

    To support this with some real numbers, a while ago I was profiling a C++ application I was writing. The application has ~200,000 lines of code, and was writing out ~3,000 values per second. This was not good enough, so I profiled, and carefully improved the "top scorers" in the profile. By changing ~200 lines (spread over a variety of classes and functions) I managed to bring the speed up to ~55,000 values per second. So that's 0.1% of the lines, and an 18 times increase in performance. That's not a bad result for one afternoon of careful coding.

    Were those 200 lines so badly written in the first place? Hell, no. They were fine. But there was a potential for improvement here, and making that improvement had a discernible effect throughout the system. I could spend the rest of my life improving the rest in the same manner, but I doubt I could get another factor two out of them.

    It goes without saying that without the profiler I could never have done this.

    For the record, I found that there were repeated calls to strlen() in a tight inner loop. The most important thing I did was eliminating that call. Smarter buffer management did the rest. The biggest remaining bottleneck is actually in sprintf (%f) - the conversion from float to string is comparatively slow. Just generating all the values without doing that conversion gets me a speed of around 180,000 values per second.

    (*) And if it hasn't, do yourself a favor and get a real development environment. Please.

  40. It is a trade-off by Trinition · · Score: 2, Interesting

    The question of Java performancd can be quite subjective. For example, I run jEdit, a 100% Java text editor. It's fast. Unforunately, its not as fast as native Win32 editors like UltraEdit or TextPad. However, my mind and body can only work so fast. Both jEdit and the other text editors are faster than I need them to be for my day-to-day operations. So, by that measure, Java is fast.

    Of course, some people interpret the statement to be a comparison to C or C++. Now, Java has a lot of behaviors that are slower than C/C++.

    For example consider array access. Java implicitlu checks the bounds of an array whereas in C/C++, that is leftas an exercise for the programmer. Unfirtunately, most pogrammers are lazy and don't exercise that. Hence with C/C++ you have buffer overruns where nasty clients can execute arbitrary code. In Java,you'd have an ArrayIndexOutOfBoundsException which would prevent the malicious data form being pushed into memory. This, it was a trade-off between security and speed.

    Garbage collection is another one of these. Ever seen a C/C++ program with memory leaks (why, I even remember the X11 libraries leaking)? With Garbage collection, your memory consumption is slower and your memory freeing slower (since Java has to determine using an algorithm what isn't used anymore whereas in C/C++ its coded into the logic). Java also seems slower becaus ethat GC overhead is generally experiences as "pauses" whereas n C/C++ the object deletion occurs through the execution of the program. But this was a trade-off. A trade-off between making developers lives easier and the programs more stable versus the speed and risk of developer-coded memory deallocation.

    Java also has immutable Strings With a mutable String class, I know I could eliminate a lot of Object creation. But the String class was made immutable so everything could be final, and thus optimized better for. This was a trade-off between the speed of Strings themselves and the speed of creating a new String everytime you need to concatenate.

    There are many more cases, but I think you get the point. Java does things ways that are slower. But many of these are trad-offs -- trade-offs to make the programs more secure, development faster and syntax/API simpler. Then they go and address the speed in other ways by improving the VM (HotSpot, incremental/concurrent GC, etc.)

    In my opinion, I would've accepted a 100% Java version of Microsoft Outlook, even if it was slower, if I didn't have to worry about the nex buffer overrun exploit hijacking my computer.

  41. bogus by khuber · · Score: 2, Interesting
    The author doesn't seem to understand what "urban legend" means. An urban legend is not the same as a myth.

    Goetz is in denial and just waves away problems using straw men without providing a truly balanced view of cases where these things cause problems. It depends on the VM, if things are done in a tight loop, and so on.

    Suffice it to say I did not like this article. As always, you need to measure application performance for yourself to find true bottlenecks.

    -Kevin

  42. Re:Java for Applications.... by james_bray · · Score: 2, Informative

    I know this is just feeding the trolls, but I couldnt resist:

    "Trying to run java applications over X at long distances makes me want to commit suicide."

    There used to be a problem with running Java on a remote X server with JDK 1.2 and 1.3, but it is fixed now in 1.4.

    "Then there is the damn JVM's that each app needs..."

    The new Isolation API slated for 1.5 should hopefully sort out the JVM-per-app isssue (I agree it's crap).

    "For some reason the screen flickers every time you run a java app"

    Again, fixed in 1.4 AFAIK.

    "Humm, and cut/paste sucks, yes you can use key combos, but sometimes in windows, its nice to select all, and copy."

    No quite sure what you mean here. If you mean in "Windows" (not windows) then you can select all and copy (CTRL+A & CTRL+C) in any Java text widget).

    "If you cant have command line, and you must have a GUI, for gods sake use a HTML."

    What??? I assume you are talking about web-based applications here? I agree, that for web applications, HTML is *usually* the way to go. However, there are some very nice standalone Java applications out there. For example (and this is not a plug, just an example), one of the best GUI CVS clients I have found is a Java application (SmartCVS).

    Just my 0.02c. I've been developing Java applications for the last 7 years (since 1.1), so I think I'm entitled to an opinion....

    James Bray

    --
    http://www.reeb.freeserve.co.uk
  43. Endless confusion by Anonymous Coward · · Score: 2, Interesting

    Many Java programmers still don't understand synchronization and Java threading. Synchronized code is slower than unsynchronized; this is normal and there's no way around it. The problem is many programmers appear to take a "just in case" approach to synchronization. For most java developers, synchronization shouldn't be much of an issue (rarely if ever should you need to mark code synchronized). Synchronized code, used correctly, doesn't have an obvious performance penalty because generally it only needs to be synchronized because of a shared resource that should be much slower than the JRE. Working with Socket springs to mind. A thread-safe container is a much more efficient approach in other cases.

    The "final is faster" stuff is totally irrelevant, even if it is true for some cases, particularly static final methods. However, final is not Java's answer to c++ inline. Final is there just to say "do not override this." If the reason it's there is for "performance," it shouldn't be there.

    The immutable object thing is equally irrelevant. Strings are a particularly pleasant illustration, taking the argument about them to its logical conclusion leaves you with an array of char. If that's what you want to work with, what you probably want is a C compiler. You can look under the hood at StringBuffer and String and try to dope out what the compiler and runtime are doing. The better approach is to think about what you're doing, and make sure you're thinking in Java. Often if strings are actually the bottleneck it's because the coder wants their perl or c approach to a problem to work, not because garbage collection is more efficient one way or the other.

    In many ways, I wish primitives weren't exposed in the language. It would be a subtle hint to those who still think with pointers, arrays and free() in the back of their head "this isn't C" and reduce the stupid performance tricks people try. I also wish prior to 1.4 javac had issued a "this isn't perl" warning if you used more than a couple StringBuffers and StringTokenizers per class. Alas, with java.util.regex those who approach every problem with "I need a regular expression that will..." can wrap their bad habits in Java code, and 1.5 seems to be devolving to c++ with crappy pseudo-templates and precompiler-ish directives.

  44. Re:Where are the Java desktop applications? by KingRamsis · · Score: 2, Funny

    because Eclipse is based on SWT not Swing.
    Swing = Sick WINdowing Garbage

  45. Simple code is more future-proof by adamsc · · Score: 2, Insightful

    That's an excellent example of what I consider the best rule for proper coding: make your goal as clear as possible. The code using array subscripting is easier for less-experienced maintenance programmers to work on and doesn't need to be replaced when you find a clever compiler does a better job.

  46. Re:To what extent does this exist in other languag by 777333ddd · · Score: 3, Interesting
    As a crude approximation, 90% of the time is due to 10% of the code.

    I think with respect to web programming, this is itself a myth. This rule of thumb seems to have reached the popular consciousness of developers in the 80s when desktop apps ruled. This was a time when each additional user adds a CPU. And it's true; in such a world, you don't worry about that other 90%. But when you have a fixed number CPUs shared by vastly more clients, you need to worry about more than just the 10% most offending code.

    In addition, I've found that programmers can be Soooo lazy that even the 90/10 isn't true in practice. I've seen the same expensive mistakes happen all over nearly every page of a web app.

    This is why so many intranet and internet applications seem slow. People put-off worrying about performance until the last step (just like they are told to). And then it might be too late.

    Developers get lulled into thinking everything's fine. Seems fast enough to them. But they are one user. Hundreds or thousands of real users will hit their app. If it's just OK for one, it's probably not OK for hundreds. Even if things seem lightning quick to you, they may not be for the hoard.

    In a lot of cases, performance can't be gained just by optimizing the little things here and there. In these cases, you often have to restructure how you approach things app-wide; you find yourself tweaking sections of almost every module. Or yanking out nice abstractions in favor of going bare metal. That takes even more time to do after the fact.

    My rule of thumb with web apps is actually to:

    1. Worry about performance throughout development.
    2. Time all page responses.
    3. Work on a slow machine.
    If you are developing a app, you will be irritated by a slow DB fetch, too many redundant fetches, or too much processing. YOU don't want to wait. YOU will be highly motivated to speed things up just for your own productivity. Budding performance issues will be detected early when structural changes are less expensive (if deemed needed). At the end of the project, you will be fixing bugs, not re-architecting for performance.

    dave

  47. Re:Double-Checked Locking by kinga · · Score: 2, Informative

    the double-checked-locking pattern is thread-safe

    Bullshit.

    The "Double-Checked Locking is Broken" Declaration.

    It has a lengthy explanation of why it is broken in Java (because of possible reordering) and also a proposal for fixing the problem. Also see Bill's paper, in which he tells of discussions he had with Guy Steele (as in Gosling, Joy and Steele, The Java Language Specification).

  48. using synchronized and a note on immutable by edlong · · Score: 2, Informative

    Perhaps the experts can comment on this one, but isn't one correct way to implement the thread-safe singleton example in the article as such:

    class SomeClass {
    private Resource resource = null;

    public synchronized Resource getResource() {
    if (resource == null)
    resource = new Resource();
    return resource;
    }
    }

    On immutable objects (string vs. stringBuffer)

    SUN itself claims that using StringBuffer is faster (e.g.
    http://developer.java.sun.com/developer/Tec hTips/1 998/tt0120.html). These 'benchmarks' are like that 'chart makers' that give you x and y percentages just to make their case look good. And in most instances, it's a specific situation that is being dealt with, which could be such a minutia element, but makes for a good razzle.

  49. White coats, step right this way... by alext · · Score: 2, Informative

    I hope that the above post is part of an elaborate joke. Otherwise, looking at this and the 455 other messages comprising the debate so far, I don't think /. is about to improve its its position in the 'where to come for Java enlightenment' stakes.

    1) Re: swapping. Java memory management will always be superior to that of the OS - OS constraints should never be greater than those applied by the VM. The memory limit of a Java process is defined with the -Xmx=nnn parameter. For production use, this should never be more than the physical memory actually available to the Java process.

    2) Re: CPU cache: By the time a CPU executes compiled code, bytecodes are nowhere near the CPU cache (they were never near the instruction cache). The fact that the code was earlier produced from bytecodes is completely irrelevant. Furthermore, bytecode compilation is persistent - compiled code is never destroyed for memory management purposes.

    3) Java and C++ optimizations: by definition, a Java JIT compiler can make all the optimizations a static compiler can make, and then some. This is because: a) the bytecode is the semantic equivalent of the source, so all source optimizations can be applied; b) it additionally has access to the complete code base, not just the equivalent of a single source file and c) it has access to the dynamic characteristics of a program, such as "branch taken" metrics, meaning that potentially indefinite refinements of the program structure are possible.

    For those that are true seekers after knowledge, I think it is safe to say that your reading time will be better spent with Sun's papers on GC or VM design, starting here, and perhaps comparing mechanisms with those of LISP machines, Dotnet or the Parrot VM.

    I also recommend getting up to speed with the new I/O, printing and regexp features found in 1.4 - a good start is Travis's JDK 1.4 tutorial, though it does not cover everything new.
    .

  50. final methods by cmburns69 · · Score: 2, Informative
    I tested out what he says about final methods and to my surprise, I found that the final methods were consistantly slower.

    An online Starcraft RPG? Only at
    In Soviet Russia, all your us are belong to base!
    Karma: redundant

    Here are the results I found, the code is below:

    First test, method1 is not final
    Running method1() TIME: 4577
    Running method2() TIME: 4596
    Running method2() TIME: 4637
    Running method1() TIME: 4547
    Running method1() TIME: 4547
    Running method2() TIME: 4566
    public static void method1() AVERAGE: 4557
    public static final void method2() AVERAGE: 4599.66

    Second test, method1 is now final
    Running method1() TIME: 4557
    Running method2() TIME: 4576
    Running method2() TIME: 4537
    Running method1() TIME: 4597
    Running method1() TIME: 4636
    Running method2() TIME: 4557
    public static final void method1() AVERAGE: 4596.66
    public static void method1() AVERAGE: 4556.66

    Here is the code I used. Its ugly, but I did it the way I did to best mitigate the effects of the JVM optimizing the code:
    package benchmarks;

    public class FinalTest {

    public static int INC;
    public static final void method1() { INC++; }
    public static void method2() { INC++; }
    public final static int TEST = 1000000000;
    public static void main(String[] args) {
    long start;
    INC = 0;
    start = System.currentTimeMillis();
    System.out.println("Running method1()");
    for(int i=0; i<TEST; i++) method1();
    System.out.println("TIME: "+(System.currentTimeMillis()-start));

    INC = 0;
    start = System.currentTimeMillis();
    System.out.println("Running method2()");
    for(int i=0; i<TEST; i++) method2();
    System.out.println("TIME: "+(System.currentTimeMillis()-start));

    INC = 0;
    start = System.currentTimeMillis();
    System.out.println("Running method2()");
    for(int i=0; i<TEST; i++) method2();
    System.out.println("TIME: "+(System.currentTimeMillis()-start));

    INC = 0;
    start = System.currentTimeMillis();
    System.out.println("Running method1()");
    for(int i=0; i<TEST; i++) method1();
    System.out.println("TIME: "+(System.currentTimeMillis()-start));

    INC = 0;
    start = System.currentTimeMillis();
    System.out.println("Running method1()");
    for(int i=0; i<TEST; i++) method1();
    System.out.println("TIME: "+(System.currentTimeMillis()-start));

    INC = 0;
    start = System.currentTimeMillis();
    System.out.println("Running method2()");
    for(int i=0; i<TEST; i++) method2();
    System.out.println("TIME: "+(System.currentTimeMillis()-start));

    }
    }
    --
    Online Starcraft RPG? At
    Dietary fiber is like asynchronous IO-- Non-blocking!
  51. JBuilder makes a case for interactive performance by jjgm · · Score: 2, Insightful

    I'm using JBuilder 8 this week. It's as good as any other desktop application on my Thinkpad R32. Sometimes I demo it to people and the coup de grace is always "... and it's written in java." which is usually responded with "but... I thought java was slow!".

    Bad interactive java is easy to write, just like bad MFC applications are easy to write.

  52. Re:To what extent does this exist in other languag by Friendless · · Score: 2, Informative

    Java has some brilliant profilers. JProbe is the one I use, but I hear that OptimizeIt is good as well.

  53. A few from C++ by Anonymous+Brave+Guy · · Score: 4, Insightful
    I wonder to what extent this exists in other languages?

    The C++ world is full of myths about what does and doesn't enhance performance. Amongst my favourites...

    1. Exceptions cripple performance.
    2. Using virtual member functions cripples performance.
    3. Using templates cripples performance.

    In each of these cases, there is some overhead involved if you actually use the language feature, but generally not otherwise with any recent compiler. However, those overheads are usually less than hand-crafting the equivalent functionality (e.g., long jumps, function look-up tables a la C) would incur. Furthermore, if you actually understand the implications of these features, you can keep the overhead way down. The next time I see someone criticise templates for code bloat, and then demonstrate in the next post that they've never come across templated wrappers for generic base classes, I'm going to have to lecture them. }:-)

    On the flip side...

    1. Passing by const& always improves performance.
    2. Pointer arithmetic is faster than array indexing.
    3. Making things const helps the optimiser to improve performance.

    Most of these get much more credit than they deserve. The first is true often, but not always: it sometimes shafts the optimiser in many compilers. The second is not true with any recent compiler. The third is true sometimes, but not nearly as often as you might expect: optimisers miss many of the apparent (to humans) possibilities anyway, and spot some of the others with or without a const there.

    As always, the rule of thumb is to write correct, maintainable code first, and then to use compiler-specific, profiler-induced hackery where (and only where) required. Whether you're writing a database or a graphic engine, this is pretty much always good advice.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    1. Re:A few from C++ by Anonymous+Brave+Guy · · Score: 2, Insightful
      Actually, exceptions can impact performance, if you are throwing the exception the majority of the time.

      Well, yes, but then they're not really exceptional, are they? Exceptions aren't intended to replace break or if.

      The point here is that just having exceptions in the language does not mean all your code runs slower. Contrary to oft-quoted opinion, the zero overhead principle does apply here with modern compilers.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.