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."

520 comments

  1. hmmm by fiftyfly · · Score: 1

    sounds like the optomizing needs a little, well, optomizing

    --
    "Sanity is not statistical", George Orwell, "1984"
    1. Re:hmmm by Anonymous Coward · · Score: 0, Troll
      Your Errors (1): Key:
      • error
        • corrected
    2. Re:hmmm by fiftyfly · · Score: 0, Offtopic

      sigh, I can't believe I misspelled it twice

      --
      "Sanity is not statistical", George Orwell, "1984"
    3. 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"

    4. Re:hmmm by fiftyfly · · Score: 1
      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"
      Actually, come to think about it, it's more like a typo in a lookup table. No, no, I've got it - it's actually not catching an error in an inlined macro until link time.

      <sigh/>

      As a matter of fact I am in the basement just now...
      --
      "Sanity is not statistical", George Orwell, "1984"
    5. Re:hmmm by Anonymous Coward · · Score: 0

      Give up already, you're just a misteak machine.

    6. Re:hmmm by Anonymous Coward · · Score: 1, Funny

      Or, perhaps you're just a moron who just can't spell reasonabl well at all....

  2. Java for Applications.... by NicotineAtNight · · Score: 0, Troll

    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.

    Also, Swing is a bloated pig.

    JNI (native interface) can swap huge numbers of arrays back and forth if you don't test for it and have a fall-back mode.

    These are huge pitfalls, even on our multi-GHZ beastly desktops. But they are the only pitfalls.

    String requires careful attention.

    That's all she wrote folks, I didn't even read the article (should probably post anonymously!) but I've spilled the beans. Nothing else to say.

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

      Also, Swing is a bloated pig.

      SWT rules!

    2. 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.

    3. 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.

    4. Re:Java for Applications.... by Anonymous Coward · · Score: 0

      And the third is substrings that keep references to their source...

    5. Re:Java for Applications.... by Anonymous Coward · · Score: 0

      Hm, so what you're saying is that strings don't require careful attention as long as you pay attention? Interesting...

    6. Re:Java for Applications.... by J.+Random+Software · · Score: 1

      After b = new String(a) and c = new String(a), b.equals(c) but b != c. No matter how much state they share, the objects themselves must be distinct--there's no way for a constructor to give you a reference to an existing object instead of creating another.

    7. Re:Java for Applications.... by linhux · · Score: 1

      Nah, not really, what I'm saying is that these specifics of Java should be dealt with so naturally you don't have to pay attention, you just do it the right way without thinking.

    8. Re:Java for Applications.... by linhux · · Score: 1

      I didn't think about this one, actually, but you're right. However, that is an implementation detail, not a language detail, really (but one could argue that it's an implementation detail shared among all(?) vendors, so it doesn't really matter).

    9. 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
    10. Re:Java for Applications.... by Anonymous Coward · · Score: 0

      What is this bs about + being a special operation of StringBuffer? String + String creates a new string so it is syntactic sugar for a String constructor me thinks. I even remember reading some java book that said it was.

      As for String needing special attention it would without StringBuffer because it would be dangerous to return a String that people could change- part of the problem with every object being a reference. StringBuffer is a just a hack to avoid String being changed unknowingly or in odd ways. Personally I would prefer just a String class and make it the programmer's reponsibility to protect the String.

    11. Re:Java for Applications.... by Idolatre · · Score: 1

      but if you do...

      String a = "very long string";
      String b = a.substring(0,1)

      a != b but a.value == b.value (a private char[] buffer that contains a representation of both strings somewhere in it)
      a.offset = 0, a.length = 16
      b.offset = 0, b.length = 1

      So even if the garbage collector gets rid of a, it won't get rid of a.value because it is still referenced by b, which means a 1 char string will use 16 bytes in memory instead of 1

      To avoid this mistake, you would have to do
      String b = new String(a.substring(0,1))
      if you intend to keep b in memory much longer than a
    12. Re:Java for Applications.... by linhux · · Score: 1

      Yes, in theory the concatenation operator just creates a new concatenated String object from the two values. However, JLS specifies that a compiler may use a StringBuffer to ease the performance penalty when doing many string concatenations, and that is exactly what most (all?) compilers do.

    13. Re:Java for Applications.... by J.+Random+Software · · Score: 1

      Ah, I had misread that as an assertion that shared state was another way to cause a == b.

      Sun's current release might do that, but it isn't part of the API. Another implementation might not, since creating garbage is so cheap that it's probably not optimal anymore.

  3. 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.

  4. 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
    1. Re:My favorite Java UL... by Anonymous Coward · · Score: 0

      That's an urban legend??? Dammit...

    2. Re:My favorite Java UL... by Anonymous Coward · · Score: 0

      I heard it was fast.

    3. Re:My favorite Java UL... by Anonymous Coward · · Score: 0

      Tell me about it! I tried installing a Solaris OS on an old Sparcstation, and X alone took 2 days to install! I can't say I know exactly how long the whole OS takes to install, because I turned the computer off after a week.

    4. Re:My favorite Java UL... by rock_climbing_guy · · Score: 1

      Actually, what you needed is some helium baloons to really make your applications fly!

      --
      Wh47 d1d j00 541, 31337 15n't t3h r0xor5 ne m0r3???
  5. Just read the article... by Anonymous Coward · · Score: 0

    Fluff. My post is superior.

  6. Source by Anonymous Coward · · Score: 1, Interesting

    Post the source code here and all "urban legends" about it will soon dissappear.

  7. 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 Anonymous Coward · · Score: 0

      This is flat out wrong, what is "heavy processing", please describe what causes your machines to run out of memory?

    2. 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.
    3. 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.

    4. Re:Java is slow by Anonymous Coward · · Score: 0

      1) I dont think you understand object oriented programming. It sounds like you were creating tons of crap when you didn't need to be. Also try tuning your garbage collector.

      2) ... and? Again tune your garbage collection. Whats wrong with using up all your FREE memory, it isn't doing anything else.

      I run a *very* complex monte carlo simulation in java, these problems don't exsist for me when acting on THOUSANDS of funds.

    5. Re:Java is slow by etymxris · · Score: 1
      Whats wrong with using up all your FREE memory, it isn't doing anything else.
      What you lose by taking up free memory is the potential for needed operations. For example, your JVM won't know that your browser needs more memory to allocate that huge PDF. Ideally, it should realize that your waiting for memory and start getting agressive about garbage collecting. But it doesn't know this. Instead, the operating system starts swapping stuff out to disk, making everything slow.

      ...tune your garbage collection
      I really shouldn't have to. I don't have to in C/C++ or (godforbid) VB. But even if I did, there would still be problems. On an inner loop I can't use any value objects since they get allocated on the heap rather than the stack. Stack allocation is O(1), heap allocation is O(N). With an inner loop, this O(N) turns into O(N^2), and so on, while the stack allocation stays at O(1).
      I run a *very* complex monte carlo simulation in java, these problems don't exsist for me when acting on THOUSANDS of funds.
      I don't doubt that Java can be made to be efficient. But you simple can't go in programming it with the same assumptions that you would with other languages. The garbage collector was supposed to make things easier. It made some things easy, but it made many other things harder.
    6. Re:Java is slow by etymxris · · Score: 1

      Yeah, that's pretty much what I was talking about.

    7. 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.
    8. Re:Java is Slow by Surak · · Score: 1, Insightful

      Remember the DOS days? Was was GWBASIC so slow? Why were QuickBASIC programs so slow? Why, later, were Visual Basic programs so slow?

      Because those versions of BASIC were all, essentially, interpreted.

      Java is essentially an interpreted language, despite JITs and JNIs and whatever.

      Interpreted languages are slow. That's why no one writes full-blown applications in BASH.

    9. Re:Java is Slow by Joe+Tie. · · Score: 1

      Then why the hell is it so slow?

      Swing.

      --
      Everything will be taken away from you.
    10. Re:Java is Slow by Anonymous Coward · · Score: 1, Informative

      I know it's a joke (and I'd mod it up if I could) but for those that are completely clueless...

      JAVA was slow about 8 years ago, when most people who would have been early adopters where making their mind up whether to adopt JAVA or not.

      Those that did, did so because the programming lanugage itself included features which made the worst kinds of common mistakes in C and C++ go away. Those that didn't, didn't because JAVA suffered from problems that are common to any new language. Unfortunately the extreme media spotlight and pressure to use the new (to most at that time) techniques of OOP only made the latter group dig in their heels and avoid any acknolwedgement that JAVA has (or even could) improve.

      It's the same kind of mindframe that still has our company operating at half duplex (since a network card we bought in '92 dropped packets like crazy on full)

    11. Re:Java is slow by Anonymous Coward · · Score: 0

      It sounds like you're talking out of your ass.

    12. Re:Java is Slow by Anonymous Coward · · Score: 0

      Why, later, were Visual Basic programs so slow

      I'll disagree with ya there, buddy. In VB (6 at least) there is an option in the compiler whether to generate P-code, which is your interpreted stuff, or straight Machine code. Move it to the latter, and your VB apps speed up when compiled.

    13. Re:Java is slow by etymxris · · Score: 1
      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.
      I'm not complaining about the implementation so much as the architecture. My project was a small part of a massive server application port from C++ to Java. C++ did not have any of these problems, but Java did. Someone else may have fubarred the application, but that's a moot point. Java is supposed to make things easier, not harder. The whole point of a garbage collector is that I don't have to understand what's going on under the hood. But the way the language works, I have to understand it in much more detail than I have to understand the relatively simple free() and malloc() of C. 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.
    14. Re:Java is Slow by iabervon · · Score: 1

      Because there's a ton of code which is "optimized" to do things in a way that Java is bad at. I mean, old objects referencing new objects is bad for modern GCs, and creating temporary objects is no problem (and happens constantly anyway). So why would you ever want to have a pool of preallocated objects which get recycled? It hurts performance, and complicates the program. Yet it's a common pattern in J2EE. You'd think that Sun would have some clue about Java...

    15. Re:Java is Slow by Surak · · Score: 0

      I knew that. I said *were* implying that this is no logner the case with VB programs.

      Many VB programs, especially shareware, tend to be slow, also, because VB programmers tend to write sloppy code, which in any language will lead to slow programs. Not all VB programmers write sloppy code, of course, but since VB is the language that many n00b programmers start with, their coding techniques tend to be very naive and without regard to performance or bloat at all. BASIC as a language also tends to encourage this because it allows you to do sloppy things like not declare your variables before use. (And yes, I know some C programmers that do this as well, and yes even in C this sloppy, sloppy, sloppy)

    16. 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!"
    17. 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.
    18. Re:Java is slow by the+eric+conspiracy · · Score: 1, Interesting

      even if you explicitly set references to null.

      Setting references to null in Java is not what I would expect from a professional programmer.

    19. Re:Java is Slow by jtdubs · · Score: 1

      You do realize that most of that is false, don't you?

      Yes, GWBASIC was interpreted. Early QuickBASIC programs were too. However, QuickBASIC introduced the ability to compile a long time ago. I have never used Visual Basic, and hence can not comment on it's implementation.

      Java is not an interpreted language. Atleast, not by default; not anymore. At "compile-time", Java is converted into a form of byte-code to be later executed by the JVM. The JVM in all recent versions of Java uses a concept you mentioned called Just-In-Time compilation because, as you said, a true interpreter is just plain slow. JIT compilation, also called "dynamic compilation" has proven to be faster than normal (or static) compilation in an increasing number of cases.

      You also mentioned JNI (Java Native Interfaces). This, of course, has nothing to do with the compiled/interpreted debate.

      As for the "no one writes full-blown applications in X", where X is an interprted language remark... you may want to talk to IBM about that as a fair amount of their development takes place in Java now-a-days. I specifically refer to Eclipse and the WebSphere family of products, including WebSphere Enterprise Developer and so on.

      Justin Dubs

    20. Re:Java is slow by Angry+Pixie · · Score: 1

      I've just found that you can't trust the garbage collector, no matter how good people say it is.

      I tried learning Java years ago precisely because of the powerful marketing SUN put behind it, but this is the first I heard about garbage collection being untrustworthy - can you elaborate?

      Question: if a person writes only portable code in C/C++ to begin with, and if Java garbage collection isn't all it's cracked up to be, does that mean Java has no real advantages over C/C++?

      Angry Pixie

    21. Re:Java is slow by GooberToo · · Score: 1

      Actually, those that serious study and implement/experiment with various GC implementations and algorithms are never happy with Java's implementation. From what I've read, there are two or three rather obvious routes they can go which should dramatically improve things, however, Sun has done nothing other than tiddle their existing implementation.

      Simply stated, as far as GC implementations go, Java's just isn't very good.

    22. Re:Java is slow by etymxris · · Score: 1
      Setting references to null in Java is not what I would expect from a professional programmer.
      Well, it shouldn't be necessary. But somewhere I read that it would help the garbage collector realize that the object referenced was no longer needed, so I tried it out. When it made no difference, I changed it back. In my pooling class I ended up having to use freaky things like weak and soft references, however.
    23. Re:Java is Slow by CognitivelyDistorted · · Score: 1
      JIT compilation, also called "dynamic compilation" has proven to be faster than normal (or static) compilation in an increasing number of cases.

      Can you tell me about those cases? As a grad student in PL, I'd be interested in hearing about them.

      What I've seen is that in many cases JIT systems can get within a few percent of static compilers, which is usually good enough. The advantage of JIT is that you have all the runtime information, e.g., target architecture, library code, etc, so you can do some optimizations that are impossible at compile-time. The downside is that the JIT has to compile really fast, so it can't do as many optimizations as a static compiler.

    24. Re:Java is Slow by Anonymous Coward · · Score: 0

      What I think is funny are some people that adopted Java 8 years ago because performance wasn't a high requirement think anyone who complains about java performance are clueless just because Java has improved.

      Anecdote: I'm not a Java person but I have a friend who loves Java and hadn't coded in C++ for quite awhile. He recently came to me with shock on his face on how fast C++ created objects. He said it had something to do with creating hundreds of thousands of objects. (Of course he still would rather code in Java)

      I have seen some nice improvements in speed of some of the java programs i've been using (don't program java myself though) But memory usage seems quite high for what they do. (This comment is pure opinion of very isolated experiences with various Java programs. Take it for what it's worth)

    25. Re:Java is slow by etymxris · · Score: 1
      I tried learning Java years ago precisely because of the powerful marketing SUN put behind it, but this is the first I heard about garbage collection being untrustworthy - can you elaborate?
      I was talking from anecdotal experience. Which while my experience is significant, it shouldn't be a substitute for actual benchmarks and cold hard analysis of the underlying algorithms.

      Question: if a person writes only portable code in C/C++ to begin with, and if Java garbage collection isn't all it's cracked up to be, does that mean Java has no real advantages over C/C++?
      Java is much more concise, and that is a huge plus. I mean, you don't program everything in assembly, sheffer strokes, or (godforbid) Turing machines. But each of these is at least as expressive as both C++ and Java. You use Java to make your life easier. A good example of this is the Serialization interface in Java. You can just serialize an object and send it over a socket, then read it on the other side. You can't do this with C++. You could do a shallow copy easy enough, but Java will automate the deep copy for you.

      There are many other things, such as Reflection. This is very useful and allows for abstraction at a level that C++ is fundamentally unable to achieve. So yes, there are many reasons to use Java, but portability is near the bottom of the list.
    26. Re:Java is slow by WolfWithoutAClause · · Score: 1

      Yeah, but that won't cause you to crash on any JVM I've ever used. What happens is it carries on allocating until it hits the limit and then starts GCing; the limit may well be megabytes- GCing takes a little while and many JVMs are tuned to avoid doing any GC if they don't have to (they benchmark better that way); but you can often adjust the JVM to GC much more often than that.

      --

      -WolfWithoutAClause

      "Gravity is only a theory, not a fact!"
    27. Re:Java is Slow by Atzanteol · · Score: 1

      I don't wish to join this little flame war, but Java is at least 'sluggish' if not slow. Want to prove it to yourself? Replace 'ls' some day with a Java version of it.

      Not to say that in many cases Java isn't fast 'enough'. I use ejb stuff and it does alright. But it keeps a *lot* in memory to do so.

      --
      "Ignorance more frequently begets confidence than does knowledge"

      - Charles Darwin
    28. Re:Java is slow by etymxris · · Score: 1
      Yeah, but that won't cause you to crash on any JVM I've ever used. What happens is it carries on allocating until it hits the limit and then starts GCing...
      Maybe I wasn't explicit. But I was talking about using up all the memory, not crashing. So the behavior you described is exactly what happened. But once you hit near 90% of your physical memory, the operating system will start pushing all sorts of things out to virtual memory, causing everything, including your application, to slow down. And when your CPU is spiked by an inner processing loop, the garbage collector which probably runs at a lower thread priority will not be given enough CPU to clear out memory fast enough.
    29. 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.

    30. Re:Java is slow by WolfWithoutAClause · · Score: 1
      If it starts to do this, you can usually change the JVM settings to restrict the initial memory the JVM has. That way it will only grow if it really needs to.

      And when your CPU is spiked by an inner processing loop, the garbage collector which probably runs at a lower thread priority will not be given enough CPU to clear out memory fast enough.

      For what exactly? The GC is supposed to free up ALL of the garbage (provided you have nulled the pointers). Anything else is a bug in the JVM; there certainly are bugs in just about any piece of software, including JVMs.

      --

      -WolfWithoutAClause

      "Gravity is only a theory, not a fact!"
    31. 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).

    32. 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!"
    33. Re:Java is slow by etymxris · · Score: 1
      If it starts to do this, you can usually change the JVM settings to restrict the initial memory the JVM has. That way it will only grow if it really needs to.
      This isn't a valid solution because sometimes your program might actually need that much memory. So you have to enable it to grow that large. But you don't want it to always grow that large. You end up with a JVM that always takes up as much memory as it can.

      As someone else pointed out, I could possibly tweak the GC settings. But this is all moot, because Java is supposed to make things easier, not harder. 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.
    34. Re:Java is Slow by WolfWithoutAClause · · Score: 1

      Hey here's a thought. I'm not trying to troll, but could it be that you're rubbish at writing Java? Seriously? I mean Java isn't magic. If you don't have insight into what's happening, it will often run slowly- same thing happens with C/C++, it's just you are probably more familiar with those languages.

      --

      -WolfWithoutAClause

      "Gravity is only a theory, not a fact!"
    35. 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!"
    36. 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.
    37. Re:Java is Slow by fmclain · · Score: 1

      Good point. Do you have a URL where we can try the code ourselves? It would be good to try this in a modern version of Java. 2 Years ago is a very long time for Java. Another thought: Benchmarks always seem to be slower in newer languages. But it's also true that those benchmarks were first written in the earlier language. What would happen to a "new" benchmark written in Java and *then* ported to C, C++, Pascal and Fortran? I remember people telling me that C++ was too slow to use for anything real.

    38. Re:Java is slow by Anonymous Coward · · Score: 0

      i agree... "well, I could make it better and more efficient by doing stuff, but I shouldn't really have to, so that means that it's not right"

      what crap.

    39. 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.
    40. Re:Java is slow by etymxris · · Score: 1
      i agree... "well, I could make it better and more efficient by doing stuff, but I shouldn't really have to, so that means that it's not right"...what crap.
      I know I'm being trolled here, but both of you are the ones full of shit. You could implement your call stack with a static array, and forgo the use of objects altogether. This would make your program fast, but it would make programming Java even worse than programming C++, probably even assembly. This is what I was talking about.

      You could also tweak the GC and force it into higher priority when the task demands, which would be a somewhat simpler solution, but still flawed. Why is it flawed? It takes CPU to do reference counting and figure out that an object is eligible for deletion. Boom, performance hit. It takes a separate thread to be able to queue and do GC in lower priority. Another performance hit, though in some cases it distributes the task more efficiently. And another. Not only do you have to check eligible objects for deletion, you also have to check ineligible objects. You wouldn't have to check if you didn't already know. In C++, the runtime knows because you tell it. In Java, it has to be figured out by the runtime itself. This wastes more CPU.

      Ok, so it's less efficient. But I shouldn't have to know this. I shouldn't have to worry about all this. The fundamental design of Java is to get rid of the complexity of C++. But it fails, because I have to know all these things to get applications of moderate complexity to work correctly. When performance is an issue, I have to put much more thought and effort into programming Java than I do C++. It wasn't supposed to be that way. So when you propose a solution that requires more effort or complexity than C++, it's automatically wrong, because it means that Java has failed as a language.

    41. Re:Java is slow by Anonymous Coward · · Score: 0

      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've parsed files as large as 1 GB, one line at a time (each was a separate immutable string, then split into several substrings). And it was fast enough that the hard drive was the bottleneck.

      The Java String object is always immutable, so what do you mean by "mutable String objects"?

      Depending on your JVM, you may need to tune the memory parameters. Sun's JVM has a low memory limit by default, I usually increase this to at least 500 MB.

    42. Re:Java is slow by WolfWithoutAClause · · Score: 1
      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.

      All I can say is that if the low priority of the GC makes your OS swap in that situation, then I would be very disappointed in that particular JVM, swapping is practically certain to slow the system down in the long run. It's a very common scenario to be continuously generating garbage, and the correct behaviour is for the garbage generating thread to try to allocate an object, fail, block and give the GC a chance to create some space and then carry on.

      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.

      It's likely to be difficult/slow to implement; the JVM would have to effectively hunt around for all the references to that object and null them out. That might well require searching every object in memory. And if it wasn't safe, then it becomes a security hole- above all Java was designed with safety in mind.

      --

      -WolfWithoutAClause

      "Gravity is only a theory, not a fact!"
    43. Re:Java is slow by etymxris · · Score: 1
      The Java String object is always immutable, so what do you mean by "mutable String objects"?
      Typo. Meant "immutable".

      I've parsed files as large as 1 GB, one line at a time (each was a separate immutable string, then split into several substrings). And it was fast enough that the hard drive was the bottleneck.
      Using char arrays rather than immutable Strings lead to a 50-75% performance improvement for me. That means the harddrive is not the bottleneck. Regular expression parsing requires complex operations to be performed on each character. Getting each line with a LineNumberReader and then calling charAt() for each character was incredibly inefficient.

      Depending on your JVM, you may need to tune the memory parameters. Sun's JVM has a low memory limit by default, I usually increase this to at least 500 MB.
      Ha! If they only gave us machines that had so much memory. Yes, I did increase the JVM memory limit. But that was a bandaid. It didn't solve the problem. If a problem would take 30MB in C++, it shouldn't take 90MB in Java. Once it got to 90MB I started rethinking my code, because 90MB was too much for the task I was performing.
    44. Re:Java is Slow by SashaM · · Score: 1

      Then why the hell is it so slow?

      Two words - "Java 2D", at least as far as user interfaces go. Before Java 2D, in the days of Java 1.1, the JVMs were slow, the garbage collector was slow and synchronous, the synchronization was slow - everything was slow. Drawing on the screen, however, was lightning fast because all of it was hardware accelerated. This meant that the user interface was very responsive, and that is what most users complain about (well, startup time too, which was also much smaller in 1.1). Try running Swing under JDK 1.1 - it's not even comparable to any recent JDKs - it's so responsive you can't tell it from a native UI.

      I even have an application for you to try.

      If I'd have to name the single most important mistake Sun made that contributed to killing Java on the desktop (not to say that it's completely dead or that it's not the other company we so love to hate didn't have a hand in it), it would certainly be the replacing of the 1.1 drawing API with Java2D. Why is Java 2D slow? Because the API promises things that are hard to implement on different platforms without resorting to drawing everything (or many things) in software.

    45. Re:Java is slow by j3110 · · Score: 1

      If you want to periodically free memory, it's just a function call away: System.gc().

      Honestly, I've never seen so many inexperienced people complaining.

      Really though, you should just let the GC run on it's own. It will run when your memory limit is hit. This is set with -Xmx 64M (which I think is the default). They have this parameter so you can make your program not eat all the system resources, which it will happily do to increase performance.

      Type java -X sometime to see all the neat things you can pass. There is a batch mode which will make your vm JIT every time instead of background JIT. There is an -Xincgc I think it's called that will give you an incremental garbage collector that will free memory as needed, or when the CPU is doing nothing useful.

      These features are here now until someone figures out a better place to put them. I think -Xbatch has been also used in -server which enables the server hotspot JIT.

      FOR YOUR OWN SAKE RTFM!!! :) If you don't have a FM, might I suggest "Mastering Java 2 J2SE 1.4" by John Zukowski. It's a great refernce book for people that know how to program, but not so well in Java. If you don't have a good book, you'll just spend most of your time rewritting the API instead of getting real work done. Also, you'll be complaining on slashdot because you don't know basic function calls like System.gc().

      --
      Karma Clown
    46. Re:Java is Slow by jtdubs · · Score: 1

      Yes, you are exactly right. As is no surprise given your background. :-)

      As you indicated, the more time you are willing to sacrafice at load-time and at "just-in-time" time, the more optimizations you can do based on that runtime information. This just isn't an option with pure "static compilation."

      So, I have a feeling that as machines become faster, enough time will be able to be devoted to JIT work to make it as fast as, if not faster than static compilation.

      I'm a bit of a computer language theorist with more interest in saving developer-time than run-time, so I'm no expert on dynamic vs static compilation issues. So, I'll take your word for it that they are in general a bit slower. I was just trying to beat back one of the more obvious trolls... :-)

      Have a good day,

      Justin Dubs

    47. Re:Java is slow by Trepidity · · Score: 1

      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.

      Sure, every good programmer should be able to do basic memory management, but in large complex programs it's not really as simple as you imply. In many cases, where an object can be referred to by arbitrarily many pointers in arbitrarily many locations, the programmer essentially has to manually implement their own garbage collection mechanism (most commonly through reference counting). This is often sub-optimal.

      I do agree that it might be a good idea to allow more tuning to the garbage collector. Instead of telling it "delete, now" though, I'd prefer something along the lines of "force the GC to run now."

    48. Re:Java is slow by etymxris · · Score: 1
      I do agree that it might be a good idea to allow more tuning to the garbage collector. Instead of telling it "delete, now" though, I'd prefer something along the lines of "force the GC to run now."
      Here's what you're looking for. Don't expect your program to be able to do anything for a few seconds when you run it. Using System.gc() or equivalent has been in my experience a bad way to keep memory usage down.
    49. Re:Java is Slow by jorleif · · Score: 1

      The slow startup time is probably one of the biggest reasons why people repeat the "Java is slow" mantra. It's more that Java feels slow.

    50. Re:Java is Slow by Anonymous Coward · · Score: 0

      1) Are you sure you've fully optimized the code in all the languages?
      2) SoE doesn't seem like a great example for performance testing--it's a pretty simple code with nice memory access patterns, etc.
      3) For actual high-performance computing (I'm talking scientific codes and the like here) a 50% difference between C++ and Java is HUGE, and even 10% is a big deal.

    51. Re:Java is slow by pyrrho · · Score: 1

      >In many cases, where an object can be referred to by arbitrarily many pointers in arbitrarily many locations, the programmer essentially has to manually implement their own garbage collection mechanism (most commonly through reference counting). This is often sub-optimal.

      no, it's optimal.

      --

      -pyrrho

    52. Re:Java is slow by pyrrho · · Score: 1

      giving hints:

      instead of stomping a reference with a new object reference, you set it to "null" first. Worked for me when I had a problem with the GC deleting a connection object that was pooled below the surface (my code just was creating a new connection, but it was reused... to get the GC to delete the proxy connection object before I created a separate one, I set it to null, as many of the java faithful recommended.

      I really think handling memory takes a lot of thought but is the most rewarding... just like thinking about data structure in the first place. Of course you think a lot about how it's arraned. Or, don't, you can have fat safe classes in C++ too.

      --

      -pyrrho

    53. Re:Java is Slow by bobintetley · · Score: 1

      Two words - "Java 2D", at least as far as user interfaces go. Before Java 2D, in the days of Java 1.1, the JVMs were slow, the garbage collector was slow and synchronous, the synchronization was slow - everything was slow. Drawing on the screen, however, was lightning fast because all of it was hardware accelerated. This meant that the user interface was very responsive, and that is what most users complain about (well, startup time too, which was also much smaller in 1.1). Try running Swing under JDK 1.1 - it's not even comparable to any recent JDKs - it's so responsive you can't tell it from a native UI.

      What? I think you are referring to AWT, which used heavyweight peer widgets (on Linux, Motif, on Windows - good ol' Win API). Swing was not introduced until Java 1.2 - the reason you "can't tell it from a native UI" is because it WAS a native UI!

      Swing uses the Window and Canvas parts of AWT to draw and manage the widgets all by itself in pure Java - hence the fact it runs slowly. This is not because Java is slow, but because it is drawing the primitives itself via Java2D (as you say) instead of taking advantage of hardware acceleration in the OS. This is also the reason Swing looks the same on any platform.

      This is ALSO the reason that Swing works AWFULLY over a remote X port - because everything is sent as bitmaps instead of primitive drawing instructions to X.

      I always wondered if it would be better to make Java2D draw with X primitives since there isn't much else out there in the UNIX world (that's used anyway), and include that pure Java X server implementation in the JRE for non-X users. This would make Swing superfast on *nix!

      As for your other remark, I'm fairly sure that Java2D does not use any hardware acceleration whatsoever (otherwise you wouldn't have that ghastly Swing over X port problem). You need to use Java3D hooked up to OpenGL/DirectX to get that.

      If it bothers you so much, you know that AWT is still there and usable in the latest JDK's, right?

      The GCJ implementation of AWT seems to be nearly complete, which is pretty damn exciting - it uses GTK for the peer widgets and hopefully should be a fair bit faster than the Sun JDK!

    54. Re:Java is slow by Anonymous Coward · · Score: 0

      Yeah, RTFM. Did you ever actually test System.gc()? I've been out of Java for a while, but up to JDK1.3 it did effectivly nothing! The VM was free to ignore it and most often it did. And with the wording in the current doc i wouldn't be surprised if there is still something fishy about it:

      Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the virtual machine has made its best effort to recycle all discarded objects.

      Suggest? Best effort? Is this a documentation or an oracle? I dont care for best effort, i want to know it's done! Yuck!

    55. Re:Java is Slow by CaptnMArk · · Score: 1

      >JIT compilation, also called "dynamic compilation" has proven to be faster than normal (or static) compilation in an increasing number of cases.

      I hope they included the startup time for that test.

      When it's true for helloworld.java, I'll believe it.

      (be sure to compare the memory footprint too, because that's the major performance killer).

    56. Re:Java is Slow by yaphadam097 · · Score: 0

      Java isn't slow. In fact, for comparable tasks it is similar in speed to C/C++. A good C/C++ programmer can increase the speed of his code beyond what Java is capable of with intelligent use of inline assembly. A bad C/C++ programmer can create code that is significantly slower than the equivalent Java code by doing stupid things that aren't even possible in Java.

      There are two areas where Java performance historically lags. The first is GUI applications. The desire to be portable coupled with the complexity of the native windowing toolkits on popular OSes has led to a lot of bloat in the Java GUI toolkits. This seems to be improving all of the time, but none of the existing GUI toolkits are equal to a native application in performance.

      The second historically bad area for Java performance is in the browser. In the early days of Java applets were seen as a way to do new things in the browser that had never been done before. Unfortunately, the stuff was buggy, the browsers lacked consistent support, and load times were often unacceptable. Since then technologies like JNLP have improved network load time and browser compatibility has improved (Both with and without Sun's plugin.) However, there is still some slow, buggy applet code out there, and there is some stiff competition from the likes of Flash.

      I am a J2EE developer, and none of this particularly matters to me. I don't write GUIs or applets when I can avoid it. To be honest, if I had to write a GUI I'd need a real good reason not to write it in C. And, I'd prefer to keep as much of my web code server side as I can and use Javascript for anything that absolutely has to be on the client side.

      I write enterprise applications, and Java is great for what I do. Load time doesn't matter much, because the server stays up with the app running all of the time. Memory footprint isn't much of an issue either, because I usually have dedicated hardware (However there are Java tools and APIs specifically designed for keeping a tiny memory footprint if that is what floats your boat.) What does matter is that Java provides a great set of APIs for doing things like distributed transaction management; interacting with a variety of databases, naming services, and other application resources; and object persistence. What also matters is that performance can be made to be consistent through a wide range of loads. I don't so much care how long it takes for one client to interact with my system, so long as the time for that one client is reasonable and the time for many, many simultaneous clients is also reasonable. That level of scalability is easy to achieve with J2EE. I don't know of any other platform I would say this about. I also care about security. Java makes decent security easy and great security possible. I don't know of any other platform where an acceptable level of security can be achieved without putting a lot of thought into it. Finally, I care that I can write pure object-oriented designs in Java without getting caught in a lot of murky areas of the language. Not that there aren't any murky areas to Java (every language has them,) but with Java it is relatively easy to keep the messy stuff out of my domain model and use all of the hallmarks of good OO design like patterns and layers.

      To sum up: Java isn't slow. C/C++ is better than Java for GUIs. Java is great for certain tasks like writing enterprise software. If I could use any language I wanted it would be Perl, but it doesn't always make sense to do so. Sometimes it makes the most sense to use C/C++ and other times it makes the most sense to use Java.

    57. Re:Java is slow by Anonymous Coward · · Score: 0

      Question: if a person writes only portable code in C/C++ to begin with, and if Java garbage collection isn't all it's cracked up to be, does that mean Java has no real advantages over C/C++?

      No, because the Java programmer will be cheaper and easier to hire than the C/C++ programmer. Which was the entire idea behind Java in the first place.

    58. Re:Java is slow by gl4ss · · Score: 1

      System.gc is very essential.. and it does work too. best effort probably means that it can't fix coding errors the programmer has made anyways, when writing long running programs for pc though it doesn't really matter and the gc should be left alone.

      with midlets it's VERY essential to use it, since some devices tend to let the memory hogging run up to the point it won't run at all before garbage collecting on their own..

      --
      world was created 5 seconds before this post as it is.
    59. Re:Java is Slow by more+fool+you · · Score: 1
      ls is not really comparing apples with oranges
      Resin includes a full-featured HTTP/1.1 web server dedicated to serving fast Java dynamic content. While Resin is tuned for dynamic content, its static file performance matches or beats Apache's static performance.
    60. Re:Java is Slow by kinga · · Score: 1

      An informed comment about GC on Slashdot! Hell just froze over...

      old objects referencing new objects is bad for modern GC

      If you assume that most new GCs are generational, since then you've got to track those old-gen to young-gen ptrs. But then it's not really "modern", c.f. Ungar 84. (It's also interesting to note that the GC in IBM's production VM is not generational.)

      creating temporary objects is no problem

      Absolutely. It's simply a pointer-bump to allocate, and it probably never gets copied between semi-spaces (and certainly never promoted).

      why would you ever want to have a pool of preallocated objects which get recycled

      Totally agree. Your pool (long-lived) is going to get promoted into the old-gen along with its transitive closure, and any time you allocate anything to put into the fields of those objects you're going to have old to young ptrs, i.e. more cardtable work plus more promotion plus more etc.

      You'd think that Sun would have some clue about Java...

      The people at SunLabs (who wrote the GC) do. Unfortunately, people elsewhere at Sun don't seem to pay them too much attention...

    61. Re:Java is slow by yuri · · Score: 1

      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. Please don't ever get involved with the JCP. Java GC may not always work perfectly but it removes a lot of bugs and save a lot of effort. Your suggestion would reintroduce those kind of bugs which show up as runtime errors in any part of the code. They would be really hard to track down, and even harder to ensure correctness of multi threaded code.

    62. 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.

    63. Re:Java is Slow by Anonymous Coward · · Score: 0

      Java's slow startup time is at least in part because it makes sure that the code it is loading is type safe (type information is preserved in the byte code). This is a good thing, as it helps prevent malicous code.

      Another reason for slower performance is that all (non-static) methods in Java are virtual (unlike C++, where this is the exception not the rule) and hence require a lookup before they are executed. This is probably why people would think final methods would be faster to call (they probably could be if the JIT used the information).

    64. Re:Java is slow by Anonymous Coward · · Score: 0

      Eh? Reference counting is f*cking slow, and notoriously unreliable (circular references, anyone?). It's almost always used simply because the developer doing the coding realizes that the memory management task at hand is far too complex for manual management but isn't familiar with writing GC's.

    65. Re:Java is Slow by GigsVT · · Score: 1

      You do sacrifice something when you change to that paradigm, the ability to exploit the ultra-high-level languages like Bash.

      Writing tight, fast-starting applications that are completely command-line driven is the ultimate in flexibility when it comes to executing multi-language cross platform code.

      Many complex things such as CORBA and COM have been developed to attempt to emulate the simple thing that the Unix shell has been doing for 20 years, a way to easily integrate disparate code modules.

      SSH is my distributed application system, Bash is my COM. It has worked extremely well for the applications I write, is very easy to maintain, and is acceptable for a large majority of applications.

      --
      I've had enough abrasive sigs. Kittens are cute and fuzzy.
    66. 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
    67. Re:Java is Slow by pi_rules · · Score: 1

      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.


      This is one thing that bugs me about the language. The smallest program will have to load up a rather large JVM. I'm waiting for the day when there's a constantly running JVM on your machine and represents one system process. A java app is started then with a java 'bootloader' of some sort that ties your new process into the JVM, or perhaps instructs the original process to suck the new byte-code into an ultra-protected type thread in the same processes making Java more of a mini-OS inside your OS. For server apps isn't not such a big deal, but for Desktop applications it could really lead to quicker adoption. Load the JVM at boot time (or 2 or 3 if your system needs different versions) then just load the bytecode into the existing JVM for each application. Distribute with a little 'task manager' type application for inspecting/killing processes and Sun might have something pretty nifty.
    68. Re:Java is Slow by Atzanteol · · Score: 1
      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.
      You mean like 'ant'? I start to get *really* annoyed after a while using ant. Build applications should still be done in C/C++/something fast (or just use 'make').
      --
      "Ignorance more frequently begets confidence than does knowledge"

      - Charles Darwin
    69. Re:Java is Slow by Ninja+Programmer · · Score: 1

      Intel sells a tool called "VTune". It includes a java profiler. If you want to know why a particular Java application is slow or not profile it and found out the answer for yourself.

    70. 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.

    71. Re:Java is Slow by pohl · · Score: 1
      So why would you ever want to have a pool of preallocated objects which get recycled? It hurts performance, and complicates the program.

      Imagine a world where memory management is not your worst enemy. In this world, worrying about garbage-collector implementation minutae such as reference age is wasted effort. This is the world where object initialization overhead is so large that keeping object pools is worth the trouble. This is the world of database connections et. al. The "complication" is only a state of mind: do you see the design pattern(s) or don't you?

      Sounds like science fiction, I know...

      --

      The "cue the foo posts in 3, 2, 1..." posts will commence with no subsequent foo posts in 3, 2, 1...

    72. Re:Java is slow by etymxris · · Score: 1
      Object o = new Object();
      o = null;
      This isn't a real test. You have to actually do something with o that will spike your CPU. As it is, the compiler could see that o is never used and optimize it away. I've even seen compilers optimize away objects that are modified and used, but never reach the user through printing or screen display.

      Some people working on the core of the product for our dot-bomb a couple of years ago had many "load" tests like this:
      Create some object;
      Do nothing important with object;
      Repeat
      Everything looked great! Then they ran a load test against the server as a whole and suddenly everything sucked. People who write the compiler certainly thought of all the simple cases. The more difficult cases are different.

      I don't have javac on my machine right now. But I would suggest doing something like:
      String s = new String("abcdefghijklmnopqrstuvwxyz");
      while (true)
      {
      System.out.println(s);
      String t = new String();
      for(int i=0; i<s.length(); ++i)
      {
      t += ((s.charAt(i) + 1) % 26) + 'a';
      }
      s = t;
      }
      This still isn't a great test, because there are very few object types. But it's better. In your test, even if o is not optimized away, the runtime can just keep giving you the same Object each and every time without actually ever deallocating it. A garbage collector that doesn't do some form of object pooling isn't worth it's weight in salt.
    73. Re:Java is slow by etymxris · · Score: 1
      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.
      Well, this is the point I've been trying to make. Java was supposed to make this stuff invisible. But for programs of even moderate complexity it shines through. So I have to write my code in a way that would makes it more complicated in Java than it would be in C++. When I have to do this, the argument about saving time is moot because I'm not saving time. So why am I using Java? I shouldn't be, at least for these tasks. And that's the point.
    74. Re:Java is slow by pyrrho · · Score: 1

      what's so slow about it? it it incrementing an int? That does take a whole instruction.

      Or is it having to call the for the pointer?

      Circular references are a design problem -- guess what, Java won't help you if you have a circular reference either!

      btw, garbage collectors always reference count, so you should mention what you want MORE than reference counting when advocating memory voodoo... I'm sorry, I mean "automatic garbage collection".

      a few Bjarne quotes:

      * The best garbage collecting language that I know of is C++ with a garbage collector.
      * If you have problems with memory management in C++, I think it is to a large extent your own fault; because either you have a problem for which the traditional C++ solutions work - in which case you use them - or you have a problem which needs a garbage collector - in which case you should use one.

      --

      -pyrrho

    75. Re:Java is Slow by Anonymous Coward · · Score: 0

      You have a point as long as all you're writing is Hello, World.

      However, most of us find it hard to get a job doing that, and are forced to work on applications that have tens or hundreds of thousands of lines of code, where the overhead and startup time of the VM become less important.

      Hint: toy examples won't convince anyone.

    76. Re:Java is Slow by dspeyer · · Score: 1
      So why is java so slow?

      I'm speaking from both experience and benchmarks. It's startup time is hideous, far worse than perl/python/bash/clisp, which are all interpretted languages (well, perl and python convert to bytecode internally, but they have to do it every time they run). It's overall performance is painful. The Great Computer Language Shootout places it between common lisp and python in overall performance (though dead last by a wide margin in startup cost). These are interpretted languages, so the bytecode excuse doesn't fly. One thing the shootout doesn't mention is GUIs. Java GUIs (whether AWT or SWING) are too slow for practical use (from my personal experience at least).

      I suspect that Java's problem is that it uses itself too much. When I run a graphical app in python, the routines that actually paint individual widgets are written in C. When I use Java, they're written in Java. This gets it some improved portability, but at a serious performance cost. Considering that there are probably no more than a few dozen operating systems currently in significant use (and fewer than ten if all UNIXen are counted together), this was a bad move.

    77. Re:Java is Slow by CognitivelyDistorted · · Score: 1
      I lost the code, but it didn't take too long to recreate. I did C# instead of VB this time. Results are here.

      If you took a Java benchmark and ported it "directly" to C (e.g., virtual methods turn into function pointers) I think that would diminish the speed advantage of C. You'd still get speedup from having structs, optimizers that have 30 years of experience behind them instead of 10, etc. But if you rewrote the thing to an equivalent hand-optimized C program, I think C would still be a lot faster.

    78. Re:Java is Slow by SashaM · · Score: 1

      What? I think you are referring to AWT

      No, I am referring to what I am referring, which is Swing. Swing was not bundled with the JRE until Java 1.2, which is why you think that it did not exist until Java 1.2.

      You can now re-read my post while assuming that I do know what I'm talking about and maybe you'll learn something new. If you still won't to believe me, I suggest you download and run the application I suggested. Hint: it runs Swing under MS VM, which is Java 1.1.4 (you can also run it on IBM's 1.1 Linux implementation).

    79. Re:Java is Slow by CognitivelyDistorted · · Score: 1
      1. I'm sure I haven't fully optimized the code in all the languages. That's a fair test for the kind of applications I have experience with, where it's more important to write reasonably maintainable code fast than to fully optimize the source code.

      2. True. My claim is that for normal code within methods, Java is almost as fast as C++. If you have lots of memory allocations and method calls, Java is definitely slower. According to the Programming Language Shootout, JDK 1.3 is 7x slower than g++ on heapsort. I'm actually surprised it's that bad. I wonder if it's better with 1.4.

      3. I don't know much about scientific computing, but I understand that Fortran is still popular because the optimizers are really good for scientific programs. I don't expect Java to meet their needs any time soon.

    80. Re:Java is Slow by CognitivelyDistorted · · Score: 1
      As you indicated, the more time you are willing to sacrafice at load-time and at "just-in-time" time, the more optimizations you can do based on that runtime information. This just isn't an option with pure "static compilation."

      Actually, you can do quite well by feeding profile information into an static compiler. There are still a few things you can't do that way, like inlining calls to DLLs. But the bigger problem with profile-driven optimization is that from what I've heard, not many developers use it. Something about not trusting really aggressive optimizers or not wanting to gather the profile information.

      I have a feeling that as machines become faster, enough time will be able to be devoted to JIT work to make it as fast as, if not faster than static compilation.

      That's a good point. I hadn't thought of that. Another thing is that the biggest problem for JITs is the startup time. Adaptive recompilation can help get good startup time while also aggressively optimizing hot spots.

      I reran my cheesy prime number benchmark today and found it was actually faster in C# than in C++. MS has some really good compiler people working for them, so I'm only mildly surprised.

    81. Re:Java is slow by CognitivelyDistorted · · Score: 1
      Incrementing the ref count is generally more than one instruction because you have to get its address first. You also have memory taken up by the ref counts, increased register and cache pressure for the increments, etc. And when you decrement it, you have to test for zero. I think ref counting would work well if you had a lot of short-lived local objects, but not so well if you had a lot of long-lived objects passed as method parameters. GCs don't maintain ref counts, btw.

      I've heard that GC can work pretty well with C++, but you can't guarantee that there won't be memory leaks because you have to assume that a declared int might really be a pointer. It would be great with a type-safe variant of C++, though.

    82. Re:Java is Slow by jorleif · · Score: 1

      Echidna certainly seems like an interesting project. It is very unfortunate that the OS is so strongly biased towards C-style runtimes, but I guess this is very difficult to avoid. This is unfortunate because it means we will be stuck with either slow startup/bad general performance or C-style programming languages. The natural selection of "right tool for the right job" becomes severely biased towards tools which are hardly optimal for describing the program one wants to create.

    83. Re:Java is slow by CognitivelyDistorted · · Score: 1
      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.

      Just to support what you're saying, I've heard that it's a common practice for C++ server/web app development shops to forbid the use of delete. Instead they restart the app periodically so it doesn't run out of memory.

    84. Re:Java is Slow by Anonymous Coward · · Score: 0

      Not to burst your bubble, but it's not very tough to write a web server that beata apache serving static content. It's been done many many times. I could probably do it in an afternoon. In Java too, which I don't even know how to write "hello world" with at this point.

    85. Re:Java is Slow by jorleif · · Score: 1

      Yes type safety is certainly an issue, but I don't think that's the whole point since many type safe environments I've used don't suffer from the same problems. I think these environments verify type-safety at compile time instead of startup time. This is of course less safe, but could be at least "safe enough" using some sort of cryptographic scheme for signing the binaries. It's probably the dynamic class loading that prevents Java from checking type safety at compile time but I'm no expert in these matters.

      The final declaration idea certainly makes sense to some degree, but there must be some reason why the JIT doesn't use the information for inlining. Is there some reason to avoid inlining of function calls in Java in general? Could it be that since most function calls have to be dynamically dispatched anyway it doesn't pay to optimize for the relatively rare case when it's possible to inline?

    86. Re:Java is Slow by alext · · Score: 1

      Were you running with -Dcompiler=none? If not, how did you manage to get Java running in interpreted mode?

    87. Re:Java is slow by CognitivelyDistorted · · Score: 1

      I tried it. Memory usage held steady. The JVM was doing a lot of collections, though, so it might be running slower than it could. Even in C, though, you wouldn't call malloc() in a tight loop if you wanted optimal performance.

    88. Re:Java is slow by j3110 · · Score: 1

      I've actually tested it... the reason why it doesn't free all memory is that it would take several seconds to do, and it would block other threads access to memory. Basically, if you are about to allocate a lot of storage, call .gc() before it and it is like telling the VM that you are going to need memory fast in a few seconds, and you can wait a few seconds now to ensure it.

      If you can't wait, or you aren't going to allocate a lot of memory soon, don't bother with it except for the occassional GC to make sure that garbage doesn't get written to swap.

      --
      Karma Clown
    89. Re:Java is Slow by Anonymous Coward · · Score: 0

      Please. Underrated? Somebody should have had some balls and moderated the parent as off-topic. Sheesh! Yes, I said sheesh!

      Surak is a well-known troll, and has been trolling off-topic shit for YEARS! How about somebody come forward and moderate this idiot appropriately? I'm doing the best I can, but I'm only one person with 5 moderator points a week. Toodaloo!

    90. Re:Java is slow by alext · · Score: 1

      Apparently the 'serious study' of Java GC you refer to has yet to absorb the fact that there are several dozen implementations widely available, many based on radically different algorithms.

      In fact, the 1.4.x Sun VM itself offers two alternatives for both the new and tenured heaps, not to mention the dozens of others available in IBM, BEA and other vendors' products.

    91. Re:Java is slow by etymxris · · Score: 1
      Even in C, though, you wouldn't call malloc() in a tight loop if you wanted optimal performance.
      Java doesn't give you the choice. In C++, objects can be on the stack, which doesn't have to be allocated. Of course, you can just bring all your variables out of the loop, but that could end up complicating your code more than porting it from Java to C++ would.

      And again, I said it wasn't a great test, just better. Replicating the conditions that I was experiencing naturally occur probably after about two thousand lines of code. And if I knew what was causing it, I might be able to reduce it to a few hundred lines. But thanks for checking it out.
    92. Re:Java is Slow by cakoose · · Score: 1
      I'm waiting for the day when there's a constantly running JVM on your machine and represents one system process.

      Yay! Please take a look at my program. It maintains a single JVM in the background and waits for compilation requests. Though this isn't really general purpose, if you run 'javac' a lot, it is pretty helpful. Now you don't have to mangle your Makefile to force it to collect a list of Java files so that it can call 'javac' just once.

    93. Re:Java is Slow by cakoose · · Score: 1
      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.
      You mean like 'ant'? I start to get *really* annoyed after a while using ant. Build applications should still be done in C/C++/something fast (or just use 'make').

      And like 'javac'? Yay! Now I get to plug my program again. It tries to make 'javac' a little faster. However, if you read the source, you'll realize that there are lots of problems with doing this in a general way. The problem is that the Java environment isn't designed to handle this.

      Some of the problems are:

      • The static crap in java.lang.System. This is really the biggest problem. I think some hacked up usage of ThreadLocals could get around this but you have to do this for every single function.
      • System.exit is really a problem. It needs to be replaced with a throwable
      • And the show-stopper, the one that made me give up on writing a general-purpose framework, is that you can't change working directories. Just to get 'javac' to work as a background process, I had convert all filenames to absolute paths.
      • The Swing classes assume that only one thread is going to be running through them (haha, sounds like they didn't think synchronization was fast enough). Though I think you can hook into the AWT event loop, I think that some of the classes may have been written with bad assumptions and running multiple threads could cause problems with static, shared code).
    94. Re:Java is Slow by mccoma · · Score: 1
      Great summary, but this line is kinda troublesome:

      This is not because Java is slow, but because it is drawing the primitives itself via Java2D (as you say) instead of taking advantage of hardware acceleration in the OS.

      From an end-user perspective, Java is slow in this instance. I love JEdit, but it crawls at times because of the UI. I can see why the Eclipse project went its own way on this one.

    95. Re:Java is Slow by cakoose · · Score: 1

      I'd expect that some may need to strip the JIT compiler out of J2ME installations.

    96. Re:Java is slow by pyrrho · · Score: 1

      > Incrementing the ref count is generally more than one instruction because you have to get its address first. You also have memory taken up by the ref counts, increased register and cache pressure for the increments, etc. And when you decrement it, you have to test for zero. I think ref counting would work well if you had a lot of short-lived local objects, but not so well if you had a lot of long-lived objects passed as method parameters.

      the question would be how can you do any less than that and achieve the same result? optimal is related to functionality. And especially, how could you have less in a garbage collection situation.

      >GCs don't maintain ref counts, btw.

      the one's I've worked with do. How could any not? you have to know if there are references left before you collect unused memory, yes? btw, the garbage collecting systems I have used have always been for the situation where you are making a lot of allocations and deallocations, so you create a separate heap (one block of new/malloced memory) from which you give out pieces. You still reference count in order to know what memory you can erase and give to another requestor. You don't actually HAVE to garbage collect if all the blocks are the same size, you can just give out slots that are free without every freeing them. Maybe you don't want to call this scheme GC? But in another more general case many sizes of short lived objects need to work in this scheme then you will actually garbage collect so that you can defrag memory from time to time.

      >I've heard that GC can work pretty well with C++, but you can't guarantee that there won't be memory leaks because you have to assume that a declared int might really be a pointer. It would be great with a type-safe variant of C++, though.

      but you can't even guarantee that in a GC system because it's possible to keep references to memory you don't need. I've seem Java programs that grow and grow and grow that don't need to, that's still a memory leak in my book. Personally, I am not looking for a language to guarantee so much as enable.

      There are two answers to memory correctness in C/C++:

      (1) remember to free what you malloc, delete what you new.

      (2) don't use pointers and arrange to manage memory entirly by scope, and in constructors/destructors (where it's relatively easy to apply rule (1).

      --

      -pyrrho

    97. Re:Java is Slow by Friendless · · Score: 1

      The JBuilder, IntelliJ IDEA, and Eclipse IDEs are all pure Java, so much so that you can copy the files from Windows to Linux and they still work. None of them have any performance problems that I can notice. Even garbage collection pauses have gone away over the last year or two.

      The product that I work on has a pure Java GUI and pure Java servers, and our performance problems are always to do with database design and unoptimised SQL.

    98. Re:Java is slow by cakoose · · Score: 1

      Have you ever tried generating the JDK 1.4 API docs with javadoc? It killed my 128MB RAM machine.

    99. Re:Java is slow by Tom+Davies · · Score: 1

      instead of stomping a reference with a new object reference, you set it to "null" first

      That's an urban myth of its own. Unless something time consuming is going to happen before a reference goes out of scope there is no need to set it to null, just wait till its stack frame dissappears.

      --
      I have discovered a wonderful .sig, but 120 characters is too small to contain it.
    100. Re:Java is slow by julesh · · Score: 1

      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.

      And how would you implement this feature? I can think of three approaches:

      - All references use a unique object serial number that is looked up in some kind of associative structure to find the pointer to the actual object. This would probably slow reference operations down by a factor of about 10, and would therefore be unacceptable from a performance perspective.

      - The 'delete' operation performs a mark & sweep operation through all data in the system hunting for pointers to the deleted object. This would work and wouldn't be unacceptably detrimental to processes that don't use it. However, I fail to see any benefit this has over 'objectref = null; System.gc(); System.runFinalizers();'.

      - References are stored as 8 bytes; 4 bytes as a pointer to the object and 4 as a unique id for the object. The object's ID is checked on each reference operation. This would probably be a bit faster than the first suggestion, but would increase memory usage by about 30% for a typical application (more for applications that use many small objects).

    101. Re:Java is Slow by bobintetley · · Score: 1

      I am aware that Swing existed before 1.2, but I recall trying to get it working under Java 1.1.8 and it took eternity to start up (JVM's fault, not Swing), and it certainly ran like an absolute dog - far worse than it does since the invention of Hotspot and the 1.4 VMs/Class libraries with Swing optimisations. Sorry if I offended you - I wasn't implying you didn't know what you were talking about, I just assumed you'd mixed AWT and Swing up.

    102. Re:Java is Slow by Evil+Grinn · · Score: 1

      The JBuilder, IntelliJ IDEA, and Eclipse IDEs are all pure Java, so much so that you can copy the files from Windows to Linux and they still work. None of them have any performance problems that I can notice. Even garbage collection pauses have gone away over the last year or two.

      I don't know about the others, but Eclipse is most certainly not "pure Java". The windows version installs several .dll files. I assume the Linux does the same with .so files.

    103. Re:Java is Slow by BenTels0 · · Score: 1

      Well, the nasty-but-I-suspect-true answer is that it has a lot to do with the programmers. Many people complain about Java programs being slow -- but by comparison, I have both seen and written programs in Java that were not slow. And I have also seen plenty of code where objects were created all over the place where you just have to ask "why?". And why the programmer didn't bother caching one object and reusing, since that was also possible...

      That aside, there's also the factor of perception (which is probably more important even than badly written code). You have to keep in mind that people's perception of the overall "speed" of a program is mostly dictated by the "speed" of the slowest part of that program. There's a small office suite out there on SourceForge somewhere which is pretty decent (word processor, basic spreadsheet, presentation package) and it performs rather nicely if you consider absolute numbers. But its perceived speed is bad because the JVM takes a relatively long time to get started.

    104. 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.

    105. Re:Java is Slow by BenTels0 · · Score: 1

      Take a look at JSR 121 over at the JCP, which is slated for the upcoming Tiger release (Java 1.5).

      It's actually interesting to see the development of the JVM, separately from the rest of the platform. Essentially it is parallelling the development of hardware-based computers, moving from being a unitask environment to finally being a multitasking environment under a managing OS.

    106. Re:Java is Slow by iabervon · · Score: 1

      There's no reason you couldn't have the programmer-visible connection objects separated from the IPC connections with slow initialization. Nothing that's available to the programmer is pooled, just the underlying resources. In particular, if you close a java.sql.Connection and open another one, you're likely to get the same connection to the database, but the object will be new (and the specification doesn't permit this object to be reused).

      So not only is it bad for performance to have pools of Java objects, but, if it's good to have pools of something, it isn't necessary to have this influence the API.

    107. Re:Java is slow by pyrrho · · Score: 1

      all I know is that I had a connection object problem connecting to a DB from java. I had a connection reference, it worked, I created the next reference (e.g. new Connection) and started my next DB connection. When the first connection object was destroyed, it interrupted my second connection. According to java syntax these were totally different connections, but in reality the connections were pooled and the proxy object called something to screw with the second proxy (to the same underlying connection, evidently). Setting the connection reference to null cured the ill as evidently the GC cleaned up sooner. This was Sun's JVM on solaris, with apache and an evidently buggy sybase JDBC .jar.

      I'm totally open to other interpretations of the events as the black hole, I mean "box", of the VM makes deep investigation all but impossible/pointless.

      --

      -pyrrho

    108. Re:Java is slow by Anonymous Coward · · Score: 0

      Just to support what you're saying, I've heard that it's a common practice for C++ server/web app development shops to forbid the use of delete. Instead they restart the app periodically so it doesn't run out of memory.

      This is complete unsubstantiated nonsense and you're an idiot.

    109. Re:Java is Slow by big-giant-head · · Score: 0

      Eclipse uses IBM's SWT gui framework. Which uses native widgets with a java interface. It is very fast, and yes you must have widgets for each platform.

      Jbuilder and IntelliJ are 100% java as is Oracles' JDeveloper, which all three run fairly well, given a minimum of 384Meg of ram.

      As a Java Developer I can see where great progress has been made in the last 5 years, but there is alot more to do. Java should be faster than it is.

      --

      So Long and Thanks for all the Fish.
  8. Memes by Zach+Garner · · Score: 1, Insightful

    Urban legends are kind of like mind viruses

    Are you new here? Usually people call this kind of thing a meme.

    1. Re:Memes by ShallowThroat · · Score: 1
      True enough, heres a source to learn about them:
      1. http://www.aleph.se/Trans/Cultural/Memetics/alt. memetics.faq.txt
      --
      The "Insert Quote Here" line is almost as predictable as inserting an actual quote.
    2. Re:Memes by Zach+Garner · · Score: 1

      Thanks for the link.. I was to lazy to give a link in my original post.

    3. Re:Memes by Anonymous Coward · · Score: 0

      Calling memes memes is a stupid meme that i don't participate in sorry.

    4. Re:Memes by dubl-u · · Score: 1

      Are you new here? Usually people call this kind of thing a meme.

      Meme is a more general term, like gene. Urban legend is a more specific term, like virus.

    5. Re:Memes by cakoose · · Score: 1

      I didn't know that "virus" is a subset of "gene".

  9. 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."

    1. Re:The best tip by fmclain · · Score: 1

      You're 100% correct on this. I've only been programming microcomputers for 25 years or so, but this is the main problem newbies seem to have. Only a small percentage of the code ever needs optimization. Since most of the cost of code is really in the maintance, (unless you worked for a .com), trashing the structure to optimize needs to be done to only that small portion of code and when it has to be done it also has to be very well documented. Unfortunatly it seldom happens that people who are optimization happy document their code well IMHO.

    2. Re:The best tip by NoOneInParticular · · Score: 1
      Good advice, but an urban legend in its own way. The "saving optimizations where it is needed" statement presumes that the code is decent enough already. Very often it isn't. Consider a situation where a C programmer passes everything (even large structs etc.) by value. Performance is hurting and he runs a profiler. The profiler cannot pinpoint a location that runs slowly, as the problem is everywhere. In this particular case, because it involves every function and every struct, there's no 10% of code that can be optimized to improve performance, no 100% of the code needs to be changed to improve it.

      Something similar can hold for Java. Because memory management is done by the GC, many new programmers are taught not to worry about MM. What they end up with is a program that has a horrible memory footprint, and there's no 10% of the code that can be improved to lessen the burden. Here again, 100% of the code needs to be optimized.

      And yes, this does happen a lot. Due to the urban legend, people are not concentrating on writing efficient (not optimized, efficient!) code, and I've seen it happen that once they finish the product is hardly deployable because of speed/memory issues that are scattered around the entire source base.

    3. Re:The best tip by Anonymous Coward · · Score: 0

      Yes, "saving optimizations where it is needed" is not always 100% of the time the best rule, but it's certainly not an urban legend. You mythical programmer still did the right thing, but writing the code first, then profiling. If he had wasted time optimizing code that wasn't slow, that would be dumb. The profiler tells him that all his code is slow. We can only hope he's smart enough to listen to the profiler.

    4. Re:The best tip by PhilHibbs · · Score: 1
      Consider a situation where a C programmer passes everything (even large structs etc.) by value.
      No single rule of thumb can save the world from an incompetent programmer. "saving optimizations where it is needed" is somewhere around numebr three or four in my rules of programming:

      1. Choose the most appropriate language/platform for the job
      2. Adhere to common good practice
      3. Test it
      4. Optimise where necessary

      Always passing large structs by value in C or C++ is cut out by Rule 2.
  10. SWT makes me want to wretch by NicotineAtNight · · Score: 1

    I wouldn't mind if it was pure Java, but that's far from the case. Pure Java GUIs can be fast (but memory intensive), it's a shame that SWT is currently the only "alternative" to Swing because it's such a horrid choice to make - Slow but pure or Difficult to use, platform-dependent and fast.

    1. Re:SWT makes me want to wretch by Anonymous Coward · · Score: 1, Informative

      SWT isn't platform-dependent. Look it up.

  11. 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.

    1. Re:Urban MySQL vs. Urban PostgreSQL by MBCook · · Score: 1
      But Linux people always say that MS stuff always crashes. And MS people say mean things about Linux.

      Does this mean Windows doesn't crash?

      Wow... My eyes have been k#dK%SDJ3(&s*x@M NO CARRIER

      --
      Comment forecast: Bits of genius surrounded by a sea of mediocrity.
    2. Re:Urban MySQL vs. Urban PostgreSQL by Anonymous Coward · · Score: 1, Informative

      While MySQL has transactions, it does not have ANSI standard transactions. They are implemented using a non-standard syntax and they don't follow the standard behavior rules.

      ANSI SQL:

      BEGIN TRANSACTION;
      BEGIN TRANSACTION;
      DELETE FROM Table1;
      COMMIT TRANSACTION;
      ROLLBACK TRANSACTION;


      MySQL:

      BEGIN;
      BEGIN;
      DELETE FROM Table1;
      COMMIT;
      ROLLBACK;


      The differences here are two fold. As you can see MySQL's syntax differs from that of normal ANSI SQL so you lose portability. Secondly MySQL permanently makes changes to the data at the first COMMIT statement so the changes can't be subsequently rolled back.

      In ANSI SQL no changes would have been applied to the data after this batch completed. In MySQL your data would be gone.

      Another point in this is MySQL's handling of corruption. It is mentioned that if you perform a full backup and keep the binary logging turned on that you can restore from the backup and replay the activity of the day. Apart from being a manual task it can be a lengthy task. Other databases simply restore themselves to the last known good state. In both cases some data will be lost, but at least in the latter case sleep wont be lost from a phone call at 4:00 AM.

    3. Re:Urban MySQL vs. Urban PostgreSQL by Anonymous Coward · · Score: 0

      Why do reports of database corruptions make you comfortable? And for that, would you exchange with me the type of wiki system you are running? Thanks.

    4. Re:Urban MySQL vs. Urban PostgreSQL by Tony-A · · Score: 1

      Good writeup.

      MySQL is maybe more "primitive", but that keeps things simpler and there are fewer moving parts to break. If MySQL isn't ready for the corporate environment, what about COBOL?

      The comparisons were done at some point in past history and are probably not all that accurate against moving targets. More a lack of interest in repeating the experiment than any attempt to mislead.

      The master --> slaves replication is powerful. Cheap and effective backup, particularly offsite backup. Check the slaves periodically. There are ways of messing up the slaves that don't bother the master.

      Cheap shot. Do a select before doing an update. The select is a much better place to discover that you have problems. The superfluous select has to be pretty cheap and in some contexts might have a negative cost in that it moves the overhead of reading the disks from write-time to read-time.

    5. Re:Urban MySQL vs. Urban PostgreSQL by Anonymous Coward · · Score: 1, Interesting

      MySQL ACID support is not commercial ready. To say it needs more battle testing and STILL select it for commercial use is quite stupid.

      I can easily corrupt MySQL with concurrent transactions in the same table with at least 2 indexes. Thanks but no thanks. MySQL, let me know when your transactions don't corrupt under real load.

  12. But it's BEATing Microsoft ! by zymano · · Score: 1

    sounds good to me.

  13. -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.

    1. Re:-1, bloody obvious by Anonymous Coward · · Score: 1, Interesting

      If it's so bloody obvious, why does it need to be said? You'd be surprised how many times people "shoot themselves in the foot" writing things in C, in areas where Java performance is (now) ok. Or write something that needs the speed in C, but introduce bugs in optimizing something that would be better optimized by the compiler anyway.

    2. Re:-1, bloody obvious by Anonymous Coward · · Score: 0

      It may be bloody obvious, but there are still some people out there who still insist on writing everything in hand-optimized assembly language.

    3. Re:-1, bloody obvious by Anonymous Coward · · Score: 0

      Hey I know you, you are this pathatic loser who is stalking Sims, hey man get a LIFE, really there you are at 37 years and you SUCK, you added me to your foe lists just because i commented on you the other day, oh god you need professional help i feel sorry for you, you will probably will die alone just like some made dog.

  14. Absolut no content by TheSunborn · · Score: 1, Insightful

    Interesting. A text that say that some things in java are not as slow as people belive, and yet it fail to deliver any prove anything. For ekample it say: synchronized methods are not slow, and yet it include no benchmark/test to backup that claim.

    And about the strings example:
    If you want't to prove that the Immutable string class is not slow the right way to do it is to make a program that make a lot of string operations and then compare the speed with one of the non Immutable string classes for java that exists.

    I really wish that the slashdot editors would read the stories and dismiss the one widtout any information.

    (Yes I know, the slashcode is free, so I could just make my own news-site but life is to short, and the studie take to much time.

    1. Re:Absolut no content by TheSunborn · · Score: 1

      (A reply to myself)
      I actuelly tried to run the benchmark
      Synchronized took 213 ms
      Unsynchronized took 22 ms

      So you can conclude that calling a synchronized function is 10 times as slow, as calling one that is NOT syncrhonized. But this does NOT matter because the actuell time it take to call a synchronized method is so small. It calls
      the synchronized method 10000000 times in ~200 meaning that you can call a synchronized method 50000 times each ms(If you already got the lock)

      So in any real program the work done in the function would far outweight the small extra time it take to call a method.

      Now I just wish they would make all the swing methods synchronized so swing would be thread safe :-}

    2. Re:Absolut no content by Anonymous Coward · · Score: 0

      Well, the author does point to an article in the resource section that tries to measure this.

    3. Re:Absolut no content by Anonymous Coward · · Score: 0

      Which jvm did you use, and on which OS?

    4. Re:Absolut no content by TheSunborn · · Score: 1

      Well but as far as I could see only for the synchronized example. It would be far more interesting to se some benchmark on the String class.

    5. Re:Absolut no content by TheSunborn · · Score: 1

      Oh, sorry forget that. It is

      java version "1.4.1_01"
      Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_01-b01)
      Java HotSpot(TM) Client VM (build 1.4.1_01-b01, mixed mode)

      on redhat linux 7.3

    6. Re:Absolut no content by Anonymous Coward · · Score: 0

      There is one place where this does matter a lot.
      Try using code that does a lot with dynamic arrays using Vector vs.... what's it's called, the newer, unsynchronized, dynamic array container?
      It can be quite measurable, if my memory serves me right, in actual programs that hammer these datastructures hard.

    7. Re:Absolut no content by JohnFluxx · · Score: 1

      Some people have pointed out that it syncronisation is horribly slow on smp machines, so perhaps making all swing methods synchronized isn't such a good idea...

    8. Re:Absolut no content by cakoose · · Score: 1

      No, it isn't a good idea. That's why they didn't do it. One of the first things they tell you when you do Swing stuff is that all mutations should happen in the event-handling thread.

  15. 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 Col.+Klink+(retired) · · Score: 1
      I love the fact that the article you linked to includes one of the Urban Legends in the original article:

      Urban performance legend #2: Declaring classes or methods final makes them faster

      From your link:

      I received a lot of feedback about this article. Here are the typical comments, together with my answers:

      "You forgot to mention that all methods in Java are virtual, because nobody is using the final keyword."

      The fact that people are not using the final keyword is not a problem with the language, but with the programmers using it. Also, virtual functions calls in general are not problematic because of the call overhead, but because of lost optimization opportunities. But since JITs know how to inline across virtual function boundaries, this is not a big deal.

      --

      -- Don't Tase me, bro!

    2. Re:Antidote by Anonymous Coward · · Score: 0
      While I agree that Java is a marketed language, I do not see where that is very relevant to the article. The article is not claiming that Java as a whole performs any better than it has in the past. The article is really prompting existing Java developers to look past some of the previous performance hotspots and concentrate on optimizing areas of a Java application that have a greater ability to be optimized.


      Despite one or two statements that imply performance improvements in the recent JVMs, I really did not get the impression that the article was trying to sell anyone that Java is faster than any other language.

    3. 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.

    4. 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!"
    5. Re:Antidote by Henry+V+.009 · · Score: 1

      If I reply to this, you are going to YHBT me, aren't you?

    6. Re:Antidote by Henry+V+.009 · · Score: 1

      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.

      Zero-time is nicer than constant time any day. Depending on the scope of the loops, your solution is about the equivalent of declaring everything globally.

      Java 1.5 will have generics.

      You missed note 2 in the text.

      Your statements on 3 seem to be based on simple ignorance. I find it hard to believe that you've never taken a look at the amount of memory your Java programs are consuming and compared it with non-Java programs. This is the least objectionable of Jelovic's points.

      Your comments on 4 ignore what Jelovic wrote: "For example, in C++ one can implement schemes that improve the locality of reference. Or allocate and free many objects at once. Or play pointer tricks to make member access faster. Etc. None of these schemes are available in Java. "

      And finally, about 5, I've seen some neat things done with template meta-programming. You don't like it because it's not elegant. And that's fair. But it still doesn't make Java faster.

    7. 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

    8. 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.

    9. Re:Antidote by Steveftoth · · Score: 1

      Also don't forget that just because you are using the final keyword doesn't mean that the method suddenly becomes non-virtual. That makes no sense.

      If you have
      class a {
      public void fun() {

      }
      }
      and
      class b extends a {
      public final void fun() {
      System.out.println("b.a");
      }
      }
      is perfectly valid code and
      A a = new B();
      a.fun();
      will execute B.fun() not A.fun() because it's still virtual.
      The only advantage the runtime system has is that it no longer has to do a vtable lookup when you KNOW that you are dealing with a B. This is only because you know that a later class cannot override the function fun().

      This does not mean that the function is non-virtual anymore though.

    10. 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
    11. Re:Antidote by Anonymous Coward · · Score: 0
      If performance was always critical, why do any of us use Perl or Python? To save time.
      Exactly, I use Python because I can write a program in Python in a couple hours that would take me a couple days in C/C++. Yeah my C++ program would run faster, but I don't think I've really written ANYTHING where performance really matters. I think the amount of time you save using Java vs. C++ is a lot less noticable than the time you save writing in Perl or Python though... but then again the speed you lose is a lot less too. I dunno, it's always a compromise.
    12. Re:Antidote by Daleks · · Score: 1

      Zero-time is nicer than constant time any day. Depending on the scope of the loops, your solution is about the equivalent of declaring everything globally.

      You're forgetting where the real work is done: in the loop body. The allocation of a single object prior to doing the real work is negligable. Also, as for the comment about global declarations, huh? If your loop body is so large that you cannot see a variable declaration as well as the entire body, your code has issues.

      You missed note 2 in the text.

      The generics in GJ provide more backwards compatability. Pizza is another story.

      Your comments on 4 ignore what Jelovic wrote: "For example, in C++ one can implement schemes that improve the locality of reference. Or allocate and free many objects at once. Or play pointer tricks to make member access faster. Etc. None of these schemes are available in Java. "

      I don't understand your comment about allocating and freeing objects in tandem. Also, I'm curious as to how accessing a data member can be made faster via a tool of memory indirection, a pointer.

      And finally, about 5, I've seen some neat things done with template meta-programming. You don't like it because it's not elegant. And that's fair. But it still doesn't make Java faster.

      Templates are hardly a panacea. You can't treat them the same way everyone has treated XML. "Oh, well let's see if we can use XML to fix this problem with our refridgerator." Their most potent use as a generative programming tool can be duplicated by hand, which honestly is sometimes easier than developing large amounts of groundwork with a template-savvy library. In this respect it doesn't make C++ any faster than Java, only easier in some situations.

    13. 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.

    14. Re:Antidote by Anonymous Coward · · Score: 0

      "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."

      dynamic casting is one of the least object-oriented things that a programmer can ever do. As such, it is generally avoided.

    15. Re:Antidote by CognitivelyDistorted · · Score: 1
      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.

      There's nothing stopping a C++ compiler from doing virtual method inlining. And many big apps benefit from custom memory managers, which are easier to put together in C++ than Java. Personally I don't like C++, but I don't think it will be the slow language any time soon.

    16. Re:Antidote by Anonymous Coward · · Score: 0

      I like OO, very much so. And I hate Java because it forces me to do all sorts of silly things just to satisfy the compiler.

      I find that my Smalltalk programs are written in a third of the time, have half the number of classes, shorter methods, and run almost as fast as C code.

      To some degree, you are blinded by the hype which does its best to NOT properly dstinguish between Java the Programming Language and all the "technologies" around it. Well done, Sun, to muddle this thoroughly.

      Having to like Java does not follow from liking OO.

    17. Re:Antidote by djelovic · · Score: 0

      Bullshit.

      If I iterate through a collection of objects and cast them to some interface, all I will ever get is dynamic casts.

      To address your other points:

      - I used Java extensively for a few years.

      - Have used all known optimization techniques to speed up all performance-critical code

      - Have used the latest JVMs

      - Checked the Sun's bug database. More often than not the bugs I stumbled upon were open for a couple of years or closed as not reproducible even though they clearly are.

      - Your logic is flawed. The fact that something works for a LOT of people doesn't make it very fast. VB worked for a LOT of people.

      - Java the language didn't change significantly since 1.2. Why you cite 1.3 as the turning point is unclear.

      - Lots of people have used Java and came out unimpressed. Contrast that with the warm and fuzzy feeling that people that have experienced, say, Scheme, ML or Haskell have.

    18. Re:Antidote by wcbarksdale · · Score: 1
      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.
      Wow. That may be the greatest abuse of big-O notation I've ever seen. Unless you somehow have a loop where nothing else is done, adding one operation to the loop causes only a scalar difference, which is not represented in big-O notation.
    19. Re:Antidote by Anonymous+Brave+Guy · · Score: 1
      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.
      And Java will never be as fast as C.

      Would it be silly to point out, that given the "zero overhead" principle of C++, those two statements are contradictory?

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    20. Re:Antidote by WolfWithoutAClause · · Score: 1

      No, I would never do that, and don't ever accuse me again, I am very offended. YHBT.

      --

      -WolfWithoutAClause

      "Gravity is only a theory, not a fact!"
    21. Re:Antidote by Henry+V+.009 · · Score: 1

      D'oh!

  16. I only have a Pentium II 266mhz and 32 megs by zymano · · Score: 0, Troll

    Yes it sucks to run java but no one uses java applets anymore. The killer app is java server side ecommerce. It's beating Microsoft so we should like it!

    1. Re:I only have a Pentium II 266mhz and 32 megs by Anonymous Coward · · Score: 0

      A Hotmail user obsfucating his email address. Whats the fucking point?

    2. Re:I only have a Pentium II 266mhz and 32 megs by Anonymous Coward · · Score: 0

      microsoft == hotmail

    3. Re:I only have a Pentium II 266mhz and 32 megs by Anonymous Coward · · Score: 0

      I said it wont work bitches

      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com
      zappa333@hotmail.com

      Important Stuff: Please try to keep posts on topic.Important Stuff: Please try to keep posts on topic.Important Stuff: Please try to keep posts on topic.

  17. 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.
  18. 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*

  19. 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.

  20. Sun is not making much off of java by zymano · · Score: 1

    news article . BEA is.

  21. 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 Anonymous Coward · · Score: 0

      Rolled them into 1.4?
      Ha! I was talking about 1.4's slowness in starting up.

    2. 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
    3. Re:Java vs. RAM by Anonymous Coward · · Score: 0

      Unfortunately Hello World still uses 8mb of ram.

    4. Re:Java vs. RAM by Anonymous Coward · · Score: 0

      If you can't spare 40MB of disk space, you need a new computer. How big do you think DirectX is? Only difference is M$ has a monopoly and can bundle it in their OS on the installation CD, so you don't notice.

    5. Re:Java vs. RAM by Anonymous Coward · · Score: 0

      > I wish I had numbers.

      Here are some:

      42
      13
      432124
      8723.37

      Have fun.

    6. Re:Java vs. RAM by WolfWithoutAClause · · Score: 1
      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!

      I believe that Hotspot only profiles the code for a while, and then switches off the profiling. The code runs a bit slowly for a short while as it is optimised and then runs at full speed.

      --

      -WolfWithoutAClause

      "Gravity is only a theory, not a fact!"
    7. Re:Java vs. RAM by Anm · · Score: 1

      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).

      Anm

    8. 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

    9. 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...

    10. Re:Java vs. RAM by Anonymous Coward · · Score: 0

      Amazing all you MS nazis that think "Java success" means "Java success on windows". Who gives a fuck if Java is slow on windows? Windows blows to begin with, and you complain that Java doesn't fix that?

    11. Re:Java vs. RAM by Anonymous Coward · · Score: 0

      who gives a fuck? ME. maybe the other 90 percent of the computing market. id rather have M$'s fast working virtual machine. go back to your linux books you know nothing retard.

    12. Re:Java vs. RAM by Anonymous Coward · · Score: 0

      ...of course, it won't seem faster because the dynamic profiling and recompiling is expensive, but the original code is running faster!

      Uhm, is this supposed to be a joke or what?

    13. Re:Java vs. RAM by james_bray · · Score: 1

      I think java resource sharing is slated for 1.5 (aka Tiger) as part of a system named the Isolation API.

      The idea being that multiple applications can be executed in a single VM whilst being "isolated" from each other.

      For more details, check out the relevant JCP page.

      James Bray

      --
      http://www.reeb.freeserve.co.uk
    14. Re:Java vs. RAM by kwerle · · Score: 1

      I think java resource sharing is slated for 1.5 (aka Tiger) as part of a system named the Isolation API.

      You may be right - I don't know. All I know is that Apple has rolled this, but I don't need to know ANY API - it just works. I hope that SUN does roll the changes as part of this, and that it also just works. Looks like the isolation stuff would/could share more resources.

      Whatever. Personally, I think SUN bites. I hope that IBM buys them, guts them, and totally opensources Java. I don't give a shit if M$ embraces and extends it - I certainly don't thnk they'll bother at this point, since they have J# (or whatever they're calling it).

      OK, it's morning and I felt the need to rant. I'm done, now.

    15. Re:Java vs. RAM by Anonymous Coward · · Score: 0

      Yes, and on MacOS X, Java with all its shared libraries comes out at...about 200MB memory image for Hello, world.

      To be fair, obviously all of that 200MB isn't even resident.

      The non-shared portion (private memory shown by top) is about 20MB.

    16. Re:Java vs. RAM by james_bray · · Score: 1

      "I hope that IBM buys them, guts them, and totally opensources Java."

      So do I. It would give the best possible future for Java. Cant see it happening anytime soon though :-(

      James

      --
      http://www.reeb.freeserve.co.uk
  22. 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
    1. Re:Performance is ok, but memory footprint... by Anonymous Coward · · Score: 1, Insightful

      I guess you already know that the OS reports each thread's memory seperately, even when all threads are in fact using the same chunk of shared memory?

      I had a funny time discovering this one out for myself when a java program I launched used 2x more than my physical memory and swap space combined.

      Of course you may ask me why I was running an enterprise application on a 486, but that's another story...

    2. Re:Performance is ok, but memory footprint... by Anonymous Coward · · Score: 0

      Why were you running an enterprise application on a 486?

    3. Re:Performance is ok, but memory footprint... by Anonymous Coward · · Score: 0

      same reason I was using Java, slow it down. I'm a Cray Salesman.

    4. Re:Performance is ok, but memory footprint... by gpoul · · Score: 1

      And you seriously want to blame Java for an application that uses too much memory?

    5. Re:Performance is ok, but memory footprint... by Anonymous Coward · · Score: 0

      Freenet's a mess. I don't know if it's the datastore or what (looking at the code quickly gave me a headache) but it's suspicious that for the relative simplicity of what it does it wants more memory and keeps more threads spinning than a heavily-loaded j2ee container (I'm thinking resin). Couple that with a bug that seems only to exist to the freenet folks (their Heisenbug) and how freenet resists jre optimization (oscilation on use/don't use -server parameter) I'd pick a different yardstick.

    6. Re:Performance is ok, but memory footprint... by Anonymous Coward · · Score: 0
      you know that memory usage and performance are practically the same thing in modern systems, right? If each Tomcat catalina container costs 16MBytes then how many web connections can I server each second on a 256MByte server?

      Java isn't slow, it's just incredibly inefficient and expensive. Probably why yahoo picked it... ooops, i guess they picked php. Any idea on what happens to java when HP buys sun?

    7. Re:Performance is ok, but memory footprint... by Anonymous Coward · · Score: 0

      Have you ever looked at the memory usage for a Java "Hello, world" (followed by an infinite loop so you can see memory usage).

      It varies depending on the platform, but it seems to range from 20MB upward.

      The Java VM starts up slowly and eats up huge amounts of memory.

    8. Re:Performance is ok, but memory footprint... by PylonHead · · Score: 1

      20MB is unlikely, but I am unsuprised to find that:

      class Hello
      {
      public static void main (String [] args)
      {
      System.out.println("Hello World!");
      while (true) {}
      }
      }

      sucks up 4,648 K, on my windows box with 1.4.1.

      --
      # (/.);;
      - : float -> float -> float =
  23. 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.

  24. 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.

  25. I'm glad it's slow... by jafo · · Score: 1

    Back in mid to late 1997, Java performance was horrible, particularly on Linux. I remember being very happy with the performance of my development box (dual PPro 200, 200MB of RAM) at the time, except when I was running Java apps. It also used tons of RAM just to start an application, and then it leaked...

    I'm sure that all of this has gotten better in the 5 years since then. It doesn't really matter to me though... After 6 months of trying to be happy with Java, I switched to Python. It's working fantasticly for me.

    Sean

    1. Re:I'm glad it's slow... by Anonymous Coward · · Score: 0

      "I'm sure that all of this has gotten better in the 5 years since then."

      Nope, it still sucks.

    2. Re:I'm glad it's slow... by Anonymous Coward · · Score: 0

      In large part because linux performance overall was terrible...
      Especially linux GUIs used to (and to large extend still do) run a lot slower than their equivalents on other platforms.
      If you're running a poorly optimised Swing application on a poorly optimised native GUI library using a non-optimised (remember, there was no official Sun JVM back then, Blackdown was hacked together over several years and never really good until Sun and Borland got involved) JVM you're asking for trouble.

  26. 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.

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

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

  28. 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 z4ce · · Score: 1

      Synchronization is an issue on non-smp boxes too. It can very easily introduce dead-lock. Remember, that a synchronized function simply tries to obtain a lock on all of the variables accessed within.

      public class A {
      public A() {
      int a, b;
      public synchronized foo() {
      a = 6;
      b = 7;
      }
      public synchronized void bar() {
      System.out.println("a = " + a + " b = " + b);
      }
      }
      Now consider the case where foo() gets the lock on variable a, a context switch takes place, bar gets the lock on b. Dead lock. A dead-lock detection algorithm will have to kick in and steal the lock from one of them, which is very expensive.

      Using synchronized methods is very dangerous from a performance perspective. Anytime you introduce a synchronized method you have to search your code for potential dead-lock conditions. Further, you have to consider how the synchronized code will reduce concurrency.

      Suppose you have:

      public class A () {
      int a,b;
      public synchronized void foo() {
      System.in.read();
      System.out.println("a = " + a + " b = " + b);
      }
      public synchronized void bar() {
      a += b;
      b++;
      }
      }

      Obviously, if your goal is do a lot more additions, synchronized is bad. The whole time you're waiting for user input, no addition can be done. Again, a potentially huge performance hit, even on non-smp.

      Synchronization is a locking mechanism. You have to take into full account the objects you are locking and how it will affect the concurrency of your program. You must consider when you should use a synchronized function or more fine locking controls (e.g. placing a.lock(), b.lock() after the read above).

      I agree with you, this article is certainly no better than the the the myths it attempts to debunk.

    2. Re:Bullshit by vlad_petric · · Score: 1
      I agree with you, except for one thing - in the example above a and b are regular ints - they don't have locks associated with it. Your example would never deadlock, as there's a single monitor (the one associated with "this")

      Anyway, the common case for locks is that they're aquired immediately - and that's how you measure their overhead.

      --

      The Raven

    3. 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.

  29. 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

    3. Re:Enough about the things Java can never fix. by Anonymous Coward · · Score: 0

      Because Sun already made the Java blows?

    4. Re:Enough about the things Java can never fix. by Anonymous Coward · · Score: 0

      I disagree. I think Python is a much better choice for keeping average programmers from blowing things up. It also interfaces very nicely with C++, if you need to do something with performance in mind. Oh, and from what I can tell Java is basically a PR tool used by Sun to fight Microsoft with. I am very wary of using either Java or C# because of this, regardless of their technical merits.

    5. Re:Enough about the things Java can never fix. by Anonymous Coward · · Score: 0

      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.

      thanks, havent laughed so hard in ages.

    6. Re:Enough about the things Java can never fix. by los+furtive · · Score: 1

      PR tool? Please. Businesses run on Java, businesses make money from Java, it's a lot more than just a PR tool. In your context you could say that Visual Basic is a PR tool for Microsoft to fight non-Windows specific languages. But we both know that they are both a lot more than that. No wonder you posted as an AC.

      --

      I'm a writer, a poet, a genius, I know it. I don't buy software, I grow it.

    7. Re:Enough about the things Java can never fix. by fredrik70 · · Score: 1

      Don't like Swing? Well you'd better like AWT.

      bah, you should try eclipse

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
  30. 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.

  31. Re:To what extent does this exist in other languag by Anonymous Coward · · Score: 0

    Well JAVA has features that are mostly missing in the languages that it is compared to.

    So any time someone compares your programming environment to say, a car, you are experiencing what most people do to JAVA.

  32. Re:The problem with exporting work by pyrrho · · Score: 1

    What you fail to understand is the real world doesn't matter. There is a special case in which that might not be true and someone might code the JVM that executes the special case, so the horrors you speak of are superfluous!

    --

    -pyrrho

  33. did you notice by andy1307 · · Score: 1

    One of the links in the sponsored content box on the left is "buy viagara online".

  34. 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.

    1. Re:Bigger synchronization myths by miu · · Score: 1
      However, the article perpetuates another myth: "Synchronization should be easy. The more things you synchronize, the better off you are."

      Exactly. This article and the resources articles make the point that sync and cache consistency cost are not themselves the problems in real code that benchmarks might make them appear. While I agree that the real clock cycle cost of synchronization belongs at the micro-optimization level, there is a great danger of creating a series of chokepoints that turns your mt-program into a single threaded program plus context switch thrashing.

      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.

      The largest problem with a 'select' based state machine is that creating a cooperative multitasking environment can be very hard to do correctly and has to be done anew for each program. I have hope for framework libraries like st-threads, but most of the projects that are at a usable point are very focused on a single type of task and don't work well with other libraries or frameworks.

      Overuse and abuse of threading is like balanced binary trees, looks good on paper, works well in your prototype, and sometimes leads to abysmal performance for reasons that can be counter-intuitive (and could lead you to learn more about memory paging, cache hits, and the like than you ever wanted to know).

      --

      [Set Cain on fire and steal his lute.]
    2. Re:Bigger synchronization myths by Anonymous Coward · · Score: 0

      Synchronization should be easy?

      Even Sun can't get it right.

      They needed three versions of SwingWorker to make it thread-safe. To me, the bug in the second version is not as subtle as they claim. In fact, it's pretty obvious.

      And last week I watched MediaTracker deadlock itself while loading several GIFs. Now I have to figure out a workaround so that MediaTracker loads the pix for my icons reeeeaaaaaal slow, one at a time...

    3. Re:Bigger synchronization myths by gokeln · · Score: 1

      Most of the issues related to threading can be mitigated using the new java.util.concurrent library coming in Java 1.5. With semaphores and message queues, multi-threading gets easier. Without the right tools, most any mundane job would be hard.

      --

      There's no time to stop for gas, we're already late.
  35. Re:To what extent does this exist in other languag by bad_fx · · Score: 1

    Yeah good point.

    Speaking of other languages, one thing I've noticed is folk applying concepts from one programming languages (or environment, system, etc) to another, maybe starting these sorts of "myths." For example applying concepts from a low level language A to a much higher level language B without much knowledge of what the compiler/interpreter/etc for B is really doing, and how it differs from A. Or even simple stuff like making incorrect assumptions about how the compiler does something can cause problems.

    Anyway I guess the point is, as you say, try it first! :) Of course you gotta be careful how you measure whether or not something degrades or improves performance. You've gotta find some way to get a measure of how only the specific change you're making affects performance, which can be tricky - ie: you end up measuring other stuff which overshadows your change, or don't do enough iterations, so the overhead involved overshadows you performance gains, etc (similar to how some sort algorithms kick ass, but only for sorting large lists,etc ). So it can be tricky deciding what's better just by throwing together a quick test.


    I guess my suggestion is don't just believe it when you're told that XYZ is good or bad programming practice. Instead, make sure you understand why doing XYZ, is good or bad.

  36. Urban Legend? Listen to Sun! by axxackall · · Score: 1, Troll
    As already discussed on /. after:
    Posted by CmdrTaco on Sunday February 09, @09:46AM
    cowmix writes "It turns out that Sun does not eat its own dog food. Specifically, this internal memo from Sun strongly suggests that Java should not be used for Sun's internal projects. More interesting still, they go on to state which other languages fullfil Java's goals better than Java does itself. Finally, the memo states Sun's own Solaris is the cause of many of Java's woes. Yikes."

    My favorite pieces to quote:

    it appears that the JRE can actually be simpler than the Python RE since Java does at least some of this work at compile time. The example above of "Hello World" is a good method for getting an idea of the minimum support code required at runtime. This support code includes garbage collector, byte code interpreter, exception processor and the like. Hello World written in Java2 requires 9M for this most basic support infrastructure. By comparison, this is slightly larger than automountd on Solaris8. The Python runtime required to execute Hello World is roughly 1.6M.

    While the Java VM (as demonstrated above) grows rapidly as more complex code is executed, the Python VM grows quite slowly. Indeed, an inventory control program written entirely in Python having a SQL database, a curses UI, and network connectivity requires only 1.7M of resident set. This seems to indicate that the resident set requirements of the JRE could be reduced by at least 80%.

    Examples include modules that used to be called Swing, RTI, IDL, JSSE and JAAS. These are all good things that should be part of Java. Our concern is that these are not separable modules which can evolve as requirements change. The Java system for evolving the interface (deprecation) does not serve production software very well. Once the interface disappears, the product just breaks.

    Production quality programs written in Java, like TogetherJ, indicate a specific Java version which must be installed before the program is run. If another program is installed, requiring a higher Java version, the user may be forced to decide which program stays and which goes away.
    --

    Less is more !
    1. Re:Urban Legend? Listen to Sun! by Anonymous Coward · · Score: 0

      You do realise that that memo is two years old, don't you?

      http://news.com.com/2100-1001-984529.html

  37. 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.

  38. 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 onelin · · Score: 1

      Right on.

      It so frequently comes up that "this language sucks" or "I prefer this for everything", when in fact, different languages can be used regularly by any given coder. Java may be the best tool for job X. C might be best for job Y, but maybe you're feeling playful and Assembly is the best job for job Z, etc... maybe even, *gasp*, a scripting language like php is the best for a certain job.

    2. Re:Why do poor coders have tunnel vision? by Angry+Pixie · · Score: 1

      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?

      Professional apathy. It's not just for civil service workers anymore!

    3. 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!
    4. 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.
    5. Re:Why do poor coders have tunnel vision? by kurosawdust · · Score: 1
      If it happens to be Billy Bob's Bug-Free Language which suits the job best, well, then, use that one.

      That is the worst euphemism for TeX I have ever heard. You'd better hope Knuth doesn't read slashdot - he's liable to tear you a new big-O for that.

    6. Re:Why do poor coders have tunnel vision? by netdpb · · Score: 1
      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.

      Unfortunately, in this day and age, it is only the knowledge of how to program the current minor release of your employer's development system that will pay your bills.

      Unless, like me, you have 10+ years of Java/J2EE experience.

      --
      /Oh, if only I had done nothing simply out of laziness!
    7. Re:Why do poor coders have tunnel vision? by Anonymous Coward · · Score: 0

      You my friend, are an arse.

      Java itself has only been around for 8 years at the most, and that's assuming you were working for Sun in 1995.

      J2EE is much newer than that.

    8. Re:Why do poor coders have tunnel vision? by SuperFrink · · Score: 1

      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.

      I think a good question to ask is how do you know which language is the best for the task?

      The other week I had a problem that dealt with sets (ie lists) of numbers. I thought of scheme right away. Yesterday I wanted to write a simple forking network server to allow me to run any text based application over a network. I chose C mainly because I could reuse some code I wrote last fall but also because I know how to use sockets in C.

      So I think knowing which tool is right for the job depends on your knowing the different tools. (If I don't know Java it won't be my first choice even it might be easy to solve the problem in Java.)

      Perhaps as important as knowing the tools is having experience with the tools, with problem solving in general and even with the particular sort of problem you are trying to solve.

    9. Re:Why do poor coders have tunnel vision? by fzammett · · Score: 1

      I agree with you 100%, but still recognize the problem with our point of view...

      In most professional programming environments, you do not have the option of choosing a language. Most businesses these days (were most programming occurs in fact), will standardize on one language or another and nothing else will be allowed. Hell, even those businesses choosing to go with .Net are picking one language or another, be it VB or C#. Very few shops will allow variations in languages.

      My shop has choosen Java. I personally find this very annoying and frustrating, not because they choose Java, but because they choose ANY one language. However, it's next to impossible to argue with the logic behind such a move... If everything everyone builds is Java, they will be able to share talents, code and the like much better than if one team uses C++, another Java and yet another VB. They will also be able to fill positions easier, assuming the choice was a reasonable one, and training will be easier too.

      It's a terrible thing for us creative thinkers and those of us that want to keep our hands in as many cookie jars as possible, but from a business perspective we are almost the enemy. Creative thought is frowned upon more and more these days in the business IT world, and it's a real shame (at the least, it's harder and harder to find a position you can enjoy).

      --
      If a pion (n-) collides with a proton in the woods & noone is there to hear it, does lamdba decay into the source pa
    10. Re:Why do poor coders have tunnel vision? by Anonymous Coward · · Score: 0

      I've been watching the job market for a while, and as far as I can tell the people doing the hiring don't care if you know _how_ to program in general (and don't even understand that concept). They care how long you have been using a specific language (or even, the really stupid ones, a specific IDE). 10 years (pretend it has been around that long) of incompetence with Java is worth far more than knowing how to program well in general. Remember- today's employers doesn't want good software, they just want good enough software for a low low price.

  39. 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
    2. Re:a lot by whereiswaldo · · Score: 1

      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.

      I remember a case with Wolfenstein 3D, IIRC. There was a note in the source or readme saying that they did something a certain (nonstandard) way because of how the cache worked on 486-class machines. In Pentium machines, it would actually be counterproductive. I might be wrong on the details, but it was an interesting note.

  40. And you're kind of right too, but.... by Anonymous Coward · · Score: 0

    JAVA designed the JVM to be a "raw" machine. That means that there is very little for it to do when it starts up. That's why the JVM starts so quickly... except:

    The last function of the JVM is to load the java library. A beastly collection of objects which comprise the JAVA language. Yes, nearly everything you use in JAVA (including the language) is modular. Hence, the machine takes more time to load your program since it's next in line (right after the JAVA language).

    If you dump the stock JVM and get one with the language libraries built in, you get much faster start times (at the expense of flexibility)

    1. Re:And you're kind of right too, but.... by Anonymous Coward · · Score: 0
      JAVA designed the JVM to be a "raw" machine.

      As opposed to what? A "cooked" machine? And I suppose everybody else designs their virtual machines to be big and slow?

      Yes, nearly everything you use in JAVA (including the language) is modular.

      If the Java platform were "modular", there would be well defined interfaces between the different parts of the libraries. Instead, everything just uses everything else. Java doesn't even have language support for modular design.

      If you dump the stock JVM and get one with the language libraries built in, you get much faster start times (at the expense of flexibility)

      Since there is only one implementation of Java (the one from Sun) and its derivatives, and they all work pretty much the same way, that is kind of difficult to do.

  41. Immutable objects do suck. by Anonymous Coward · · Score: 1, Interesting

    for example:

    public String indent(int indent)
    {
    String output = "";
    for (int x= 0; x indent; x++)
    {
    output += "\t";
    }
    return output;
    }

    If you use this function you are waisting cpu power like crazy because strings are immutable. This has nothing to do with the jvm, but is inherent in immutable strings, no matter what language they are in. Here's the reason... output starts as an empty string then the first "\t" is added to it. What the compiler MUST do is create a 3rd string of the length of both output and the "\t" string. Then it copies all of output in to the new string then the "\t". On the next loop output = "\t" and we add another "\t". To do this we make a third string again and start copying. BUT we already copied everything in output to a new string once already, so we're copying it for a second time. This is where we waste cpu cycles, and this is why not using immutable strings properly can cause problems. By the end of the function, the first "\t" is copied indent number of times, to indent number of temporary objects. If we change the function to..

    public String indent(int indent)
    {
    StringBuffer output = new StringBuffer();
    for (int x= 0; x indent; x++)
    {
    output.append("\t");
    }
    return output.toString();
    }

    No temp strings are created. No "\t"'s are copied. Thus we don't waste cpu cycles.

    1. Re:Immutable objects do suck. by Anonymous Coward · · Score: 0

      Amazing, a post by an AC who failed to read or comprehend the article...how original.

    2. Re:Immutable objects DO suck. by glenebob · · Score: 1
      "Read the article. It thoroughly explains why you're wrong."
      *Ahem*, maybe you should read the article. It does nothing to explain why immutable objects do or do not suck. The article does not explain why the parent post is wrong.

      All the article says is that creating a new immutable object is about the same as assigning to an existing one. It strangely avoids demonstrating the use of a concatinate() method on a mutable object, and instead compares concatinating three immutable objects in two slightly different contexts.

      The two examples given by the parent post are indeed very different, and do explain nicely why immutable objects can suck when used by a naive programmer.

    3. Re:Immutable objects do suck. by japer · · Score: 1

      Even more efficient is to give your stringbuffer a resonable default size, this way it doesn't have to waste time + memory growing. This is true of many Objects in java that resize automagically as required. (ie Vector). I've not yet come across a situation where I couldn't estimate a good default size for these types of Objects.

    4. Re:Immutable objects do suck. by Anonymous Coward · · Score: 0

      The best answer if you're doing something as contrived as this example is an array of char. That's what it's there for.

    5. Re:Immutable objects do suck. by v_1_r_u_5 · · Score: 1

      for (int x= 0; x indent; x++) output += "\t";


      There are MANY situations when immutable objects suck, and you've mentioned a good one with regards to speed. Let's say that the variable indent equals 1,000,000. If you use an immutable object, this loop creates 1,000,000 objects and uses at least 500,000,500,000 bytes of ram [n*(n+1)*.5]. With a mutable approach, the lower bound is only 1,000,000 bytes for the entire loop and you'll only create one object instead of one million.

  42. that's kind of a pathological case though by Trepidity · · Score: 1

    I do agree this is a problem, but in many cases the Java behavior is actually better; a lot of C/C++ slowdown is from realtime memory management, and could be sped up by saving up stuff to do later (this can be done manually with C++ allocators, but is often a pain in the ass).

  43. Re:Urban Legend: IBM is unbiased regarding Java by Prof.Phreak · · Score: 1

    They're actually quite open about it. I took a websphere class with'em, and the consultant made many funny remarks about microsoft, c#, and even sun. (their eclipse does that do the sun???)

    --

    "If anything can go wrong, it will." - Murphy

  44. Does anyone have a mirror? by Anonymous Coward · · Score: 0

    I keep getting a time-out whenever I try to access it.

  45. Where are the Java desktop applications? by Anonymous Coward · · Score: 1, Interesting

    Where are the Java spreadsheets, browsers and word processors? They don't exist. Why is that? This is not a flame - if the Java language is as good as C++ then why are all critical feature-filled applications that you use every day written in C or C++?

    Don't moderate - post an example of a useful java desktop application.

    1. 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.

    2. Re:Where are the Java desktop applications? by Anonymous Coward · · Score: 0

      Corel's Java Word Perfect was a disaster, Open Office uses Java minimally for just glue code and HotJava is a sick and twisted joke. You hit the nail on the head - you just don't know what crazy JVM version people ultimately have - and no one wants to download a 40 meg Java distro.

    3. Re:Where are the Java desktop applications? by Anonymous Coward · · Score: 1, Interesting

      HotJava is dead. I stopped by the website a couple weeks ago and Sun had a notice saying that HotJava was now in "end of life" cycle. Too bad. It would have been nice to have *one* browser that worked the same on *any* platform which supported Java.

    4. 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.

    5. Re:Where are the Java desktop applications? by Anonymous Coward · · Score: 0

      Java WordPerfect was killed because they were trying to run it on Pentium 90s. I tried it on a PII-400 and it put C++ bloat explosions like Mozilla and OpenOffice to shame in terms of responsiveness. Just see ThinkFree Office -- it works fine.

    6. Re:Where are the Java desktop applications? by Lairdsville · · Score: 1

      Check out Eclipse, from IBM. I didn't believe Java was any good for desktop applications until I played with Eclipse.

    7. Re:Where are the Java desktop applications? by oogoliegoogolie · · Score: 1

      Righto! Eclipse doesn't even feel or behave like the java apps we have come to know and love-it's fast, responsive, doesn't slow the rest of the system down. What is it doing that other apps aren't?

    8. Re:Where are the Java desktop applications? by oogoliegoogolie · · Score: 1

      Because noone in their right mind is going to take their tried and true C++ office suite that runs find and dandy and rewrite it from scratch in another language. We all know how sucessful Corel was at this.

      BTW, I did a search and immediately found office suites and apps written in java. And no, I never heard of these products but the reason you don't hear about them is the same reason you hear very little about Corel office or Smartsuite nowadays-most people have tunnel vision and don't even notice the others as they run for MS Office, or in the case of slashdotters, Openoffice.

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

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

    10. Re:Where are the Java desktop applications? by truth_revealed · · Score: 1

      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.

      Slashdot tip #53: When annoying 'facts' get in the way - invent a buddy!
      Watch in awe as Java zealots mod up a baseless pro-java post based on second-hand hearsay!

      Hearsay
      Any evidence that is offered by a witness of which they do not have direct knowledge but, rather, their testimony is based on what others have said to them. For example, if Bob heard from Susan about an accident that Susan witnessed but that Bob had not, and Bob attempted to repeat Susan's story in court, it could be objected to as "hearsay." The basic rule, when testifying in court, is that you can only provide information of which you have direct knowledge. In other words, hearsay evidence is not allowed. Hearsay evidence is also referred to as "second-hand evidence" or as "rumor." You are able to tell a court what you heard, to repeat the rumor, and testify that, in fact, the story you heard was told to you, but under the hearsay rule, your testimony would not be evidence of the actual facts of the story but only that you heard those words spoken.

    11. Re:Where are the Java desktop applications? by Anonymous Coward · · Score: 0

      Here's two.

      http://www.eclipse.org/
      http://www.netbeans.org /

    12. Re:Where are the Java desktop applications? by jasonditz · · Score: 1

      Fortunately this isn't a courtroom, and the fact of the matter is valid logic and court proceedings aren't neccesarily identical. Hearsay isn't a logical fallacy. The fact of the matter is, when I last used Java WP it was on a Pentium 133... and while it did everything it was supposed to, it was painfully slow. The notion that now, on a Pentium 4 that is 20+ times as fast, the slowness isn't noticable any longer shouldn't require much of a suspension of disbelief. I don't use WP anymore, and would be lying if I said I did. I know of at least one person in the universe who still does, however, and he says it performs nicely on his P4, I see no reason to doubt him.

    13. Re:Where are the Java desktop applications? by Anonymous Coward · · Score: 0
      Where are the Java spreadsheets, browsers and word processors? They don't exist. Why is that? This is not a flame - if the Java language is as good as C++ then why are all critical feature-filled applications that you use every day written in C or C++?


      Even Sun's own StarOffice word processing app is written in C++! That's why it's not available for the Apple line of computers -- they can't port it!

      Sun's marketing propaganda is so good that Java fanboys overlook this fact.

      a) If Sun actually practiced what they preached,
      They wouldn't have needed to purchase StarOffice from the German developers who created it. Sun has literally 30,000 employees. None of them could whip up a word processor?
      b) If Sun actually practiced what they preached,
      writing StarOffice in Java could have solved the cross-platform dilemma. "Write once, run everywhere"? It's more like "Write once, break everywhere".
      c) So now Sun HAS the source code to StarOffice. They even open sourced it. So WHAT IS THE DELAY IN PORTING IT TO JAVA?

      Finally, if Java worked as advertised, you would not have to have products such as OptimizeIt (TM) from Borland, which tries to address Java memory leaks. The garbage collector does NOT work as advertised. Even if you run system.gc( ), it's won't always work.

    14. Re:Where are the Java desktop applications? by duck_prime · · Score: 1
      Where are the Java spreadsheets, browsers and word processors?
      Yeah, I double-clicked on their icons back in '01 and they're still loading!
    15. Re:Where are the Java desktop applications? by Anonymous Coward · · Score: 0

      I use Sun One Workshop for Java Development.
      It works very fast and well.
      I think this program is comparable in size, processing and complexity to Microsoft Word, So I don't see why there is any problem with java desktop apps.

    16. Re:Where are the Java desktop applications? by Euphonious+Coward · · Score: 1
      Strangely enough, a much faster machine doesn't necessarily mean much faster execution. If the bus isn't much faster, if the disk isn't much faster, if the program doesn't work nicely with the cache, then a 2GHz P4 might not run it more than (say) twice as fast as a 300 MHz P2. In fact, a 2.4 GHz P4 is slower than a 1.4 GHz P3 for many programs.

      So, speculating that (apparently) faster hardware would take care of the performance problems isn't good enough -- you really have to have run it yourself. There are sound evidential reasons for the hearsay rule.

    17. Re:Where are the Java desktop applications? by jasonditz · · Score: 1
      If the bus isn't much faster, ...

      Yeah, I'm sure the bus speed difference between a P133 and a Pentium 4 is negligible...

      Since the program in question is basically the Java Virtual Machine, I'm certain most of us have noticed that a P133 with 32 MB of EDO RAM is just the teensiest bit slower than a P4 with half a gig of RDRAM in running it.

      As I said, the last experience I had with WP for Java was on a mid-range Pentium... 5 years ago. It did everything it was supposed to, but was miserably slow.

      Now, let us suppose that at least a plurality of the people on slashdot accept the notion that Java apps run at the very least noticably faster when you go from a 5-6 year old Pentium to a modern system with 16x as much RAM, of a far greater speed I might add, AND a processor capable of doing more than 20x the instructions per second.

      Now think about the notion that WP for Java would be faster on the faster system... still sound so crazy?

    18. Re:Where are the Java desktop applications? by giraffecock · · Score: 0

      As strange as it may seem, i shit in you grandmothers cunt.

      i have solid evidence of this.

  46. I think that was his point by Anonymous Coward · · Score: 0

    The underlying point of the article was not that X is fast or Y is slow, but that you should be skeptical of blanket statements like "X is fast" or "Y is slow", because (a) these statements are highly time-dependent (JVMs get better), (b) they are highly JVM-dependent for the reasons you state, and (c) they are also dependent on other factors.

    BTW, your point about final methods makes a bad assumption on the limits of optimization. A smart optimizer would figure out that no other loaded class overrides a given method, and would optimize accordingly, whether or not you've hinted so by declaring it final (and if a class was loaded later that overrode that method, the JIT would invalidate code that depended on this assumption.) I'm pretty sure that TowerJ did this.

    1. Re:I think that was his point by vlad_petric · · Score: 1
      A smart optimizer would figure out that no other loaded class overrides a given method, and would optimize accordingly, whether or not you've hinted so by declaring it final.

      I agree with you, up to a point - in Java the class hierarchy is dynamic, so you can always load a class that screws up the compiler's assumptions. Now the overhead of recompiling everything is too big, so most JVMs are just extremely conservative about it. Towerj supports only limited class loading (IIRC) so it can do it well, but that's not "Java"

      --

      The Raven

  47. Re:To what extent does this exist in other languag by Surak · · Score: 1

    I guess my suggestion is don't just believe it when you're told that XYZ is good or bad programming practice. Instead, make sure you understand why doing XYZ, is good or bad.

    Of course that's half the problem. The article mentions two programming practices, and each of them have a grain of truth. The sync/unsync issue used to be true, and the other one, the use of the final delcaration, seems to make sense but it doesn't actually work that way. Hence the reason I suggest that people actually try something before accepting even a seemingly plausible explanation for what amounts to voodoo programming practice.

  48. 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?

    1. Re:Hardware manufacturers want slow software. by CognitivelyDistorted · · Score: 1
      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.

      I've heard that too, but I don't think it's true. Basic economics says that if a product is more useful, customers will pay a higher price for it. That's why manufacturers try to make the hardware faster. Shouldn't faster software be just as good from their point of view?

      However, that's only basic economics. I could believe that there were some strange economic conditions affecting DEC business strategy. Or maybe that DEC was just stupid. That would explain their nonexistence. But Intel spends a lot of money maintaining an optimizing compiler and helping software vendors optimize their code. So it doesn't seem to be true now.

    2. Re:Hardware manufacturers want slow software. by Angry+Pixie · · Score: 1

      It all depends on how closely tied the software developer is to the hardware developer. It was true with VAX and it's true with Wintel today.

      It makes a pretty S-curve. Toward the bottom an independent software developer has an incentive to optimize his/her product in order to compete with the big guys. (i.e., Alchemy Mindworks)

      At the middle a developer partnered with a hardware maker has an incentive to encourage component upgrades (BioWare & NVIDIA).

      At the top, a developer also makes the hardware or otherwise controls hardware design, and so can encourage whole platform upgrades.(MS + Intel)

      Yes, I believe Microsoft owns Intel and that DEC really played a part in its own demise.

    3. Re:Hardware manufacturers want slow software. by pyrrho · · Score: 1

      >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?

      exactly.

      I think that's the real beauty of unix/linux, both were in the hands of their user, software engineers and system deployers. It's not quite what RMS is talking about, I don't think, but he's facilitated it with a license that retains their power better than the public domain did before. Then the other beauty is just being implimented over and over which is good for any technology, however flawed it might be.

      --

      -pyrrho

    4. Re:Hardware manufacturers want slow software. by pyrrho · · Score: 1

      you are correct with regard to your ideas but it works like this:

      the software engineers start before the machine it will run on is actually available. They have to guess. They want to put a lot in their software, so (until recently) that meant they were limited by the machines resources, and when the company helps direct them to be aggressive in what they try, the end result is that the machine is not ready for the tasks they put it too, and they did not write optimal code in terms of resource usage.

      i think.

      --

      -pyrrho

    5. Re:Hardware manufacturers want slow software. by CognitivelyDistorted · · Score: 1

      You just reminded me of some more basic economics. The point of a monopoly or cartel is to make more profits by creating artificial scarcity. Intentionally writing slow code would be a way of doing that, but it only works if you have limited competition. Which may be the case with your bigger examples. Hard to say from my armchair. Certainly could have been true back when IBM was the only major manufacturer.

    6. Re:Hardware manufacturers want slow software. by Angry+Pixie · · Score: 1

      All economic theories come down to the choice between guns and butter, so generalizations have to be made. :)

      If the software becomes too demanding, it will make it that much easier to push the requisite next-gen hardware component. I mentioned NVidia and BioWare because of Neverwinter Nights. It really wants me to buy a better GeForce card.

  49. Java is faster than most people think it is. by Anonymous Coward · · Score: 0

    There are some performance issues with Java. That's a fact. But, on the other hand, Java is faster than most people think it is: take a look at http://www.jrman.org for an example of a Renderman renderer written in Java which is much faster than Aqsis (a renderman renderer written in C++)

  50. Depends on what the meaning of the word is, is. by Latent+Heat · · Score: 1
    SWT is not platform dependent inasmuch as there is a SWT implementation for Windows and implementations for other platforms are "almost as far along."

    SWT is platform dependent in the sense that you have to include a different package with your SWT app to make it work with each supported platform. This is in a way true with Swing, but since Swing is SUN-sanctioned, the customizations for a particular platform are part of the JVM for that platform so the distribution of a Swing app is more transparent.

  51. not just java by minus_273 · · Score: 1

    i think this is prevealent in other laguales if not all other aspects of computing.

    the fact is most people take one method to be faster than another without ondertanding the reason behind it. how often do people look at the number of sys calls or O() of a funstion they use. Simply put if you dont have some sort of theoritical backing to you claim that one method id faster than another, it cant bebelieved.

    --
    The war with islam is a war on the beast
    The war on terror is a war for peace
    1. Re:not just java by fizbin · · Score: 1
      Simply put if you dont have some sort of theoritical backing to you claim that one method id faster than another, it cant bebelieved.

      I'd revise this statement to: "if you don't have some sort of evidence (experimental or hard theoretical) backing to your claim that one method is faster than another, your claim can't be believed."

      I don't care what the theory says should happen; if the experimental evidence says something different, the theory is wrong. (Sometimes because it's based on bad CS, sometimes because it's based on faulty assumptions about how various classes actually do behave internally)

      And be wary of relying on O() calculations when the relevant n is in your program really very small. It's also a mistake to calculate O() without taking into consideration the whole operating environment.

      The best example I can think of here is using different List implementations as queues. If you just go blindly by a naive O() calculation, the LinkedList class is the obvious choice, but:
      • LinkedList does not exhibit O(1) behavior on queue operations for sufficiently large queues, and
      • Depending on environment, it takes a queue size of about 30 before its performance edges ahead of ArrayList

      I investigated this closely after reading this article. Note that my first attempt at a CircularArrayList (implemented without first inspecting his code) ran about 10% slower than the code given in the article, though I gradually was able to tune it to comparable speeds.

      The lesson from all of this is: "program performance should be treated as experimental science".
  52. I'm taking the bait by Jimithing+DMB · · Score: 1

    Umm... MoneyDance?

  53. mod him up by los+furtive · · Score: 0, Offtopic

    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.

    Somebody mod this guy up, those are the best lines I've seen all night.

    --

    I'm a writer, a poet, a genius, I know it. I don't buy software, I grow it.

  54. Wrong. by Anonymous Coward · · Score: 0
    Thus, someone not familiar with Java may accidentally generate huge amount of StringBuffer objects in loops.
    Any decent compiler will use a single StringBuffer object for the duration of the loop. It's an incredibly basic optimization.
    1. Re:Wrong. by linhux · · Score: 1

      How are they supposed to do that in a loop like:

      for (;;) {
      String q = a + b + c;
      String r = q + c;
      blaha(r);
      }


      This will, as far as I can see, inevitably create two StringBuffer objects per iteration (or one of a, b and c are constant, in which case the first string concatenation can be optimized away).

    2. Re:Wrong. by Anonymous Coward · · Score: 0

      Let me say up front that I don't know java, but the following loop looks really bad.

      in your example,
      for (;;) {
      String q = a + b + c;
      String r = q + c;
      blaha(r);
      }

      having a class constructed and destructed on the stack twice for every loop iteration seems downright inefficient. Perhaps things work differently in java than they do c++.

    3. Re:Wrong. by linhux · · Score: 1

      Yes, the example is quite inneficient, that was the point. :-) But unexperienced Java developers actually write this kind of code. And it's actually four objects being contructed for every iteration (two String and two StringBuffer objects).

      But also, modern JVMs are quite optimized to handle small temporary objects, so while the performance will be bad, it might not be as bad as one first thinks.

  55. *Paying*? by Anonymous Coward · · Score: 0

    What kind of Loonix hippie are you?
    Tell Transgaming to fuck themselfs and go and pirate a copy of 98 to play your games.

  56. Drying the dog by Skapare · · Score: 0, Offtopic

    How does anyone really know for sure that some urban legend really did not happen? Take the dog drying case. It's certainly plausible, as urban legends do stick around when that is the case. But a microwave oven is actually a lousy way to dry a dog (or anything for that matter). This legend, though, might have been derived from a case in the late 1960's when a woman in Ohio did (try to) dry (and did kill) her dog in a conventional oven.

    If you really want to dry your dog safely, you need to get one of these.

    --
    now we need to go OSS in diesel cars
    1. Re:Drying the dog by antirename · · Score: 1

      It did happen, at least once that I know of. The lady had a very small dog, and Alzheimers. The microwave was fine, the dog was not. Not as spectacular and messy as you might have heard, although the smell was unbelievable.

  57. 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 yaphadam097 · · Score: 1

      Excellent post, I agreed with everything you said. Although I would add that a lot has been done to improve synchronization and garbage collection in 1.4.x and the article might have taken that for granted.

      Some bigger issues for server-side design: be careful ... how you use persistence (such as JDO).

      I have spent many many hours optimizing crappy persistence code. It has been my experience that JDBC code is the biggest source of performance problems on most Java projects. However, the amount of time I spend fixing performance problems in JDBC code has dropped to almost zero since I have been using JDO. There are really only a couple of rules to follow with JDO:

      1. Do non-transactional reads whenever possible.
      2. Perform writes asynchronously whenever possible.
      3. When using JDO with J2EE wrap the JDO code in a session facade (Or message facade) and use container managed transactions.
      Other than that it has been my experience that JDO code performs very well and has very few opportunities for mishaps.
    3. Re:The article is wrong by jareds · · Score: 1

      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.

      An UnsynchronizedStringBuffer will indeed be faster, but I don't understand your proposal for how StringBuffer could modify itself in a thread-safe manner without using synchronization. Could you explain? This seems quite impossible.

    4. 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.

    5. Re:The article is wrong by jdennett · · Score: 1

      LOL.

      I don't ask that people believe me blindly. Just don't believe any performance reports blindly.

      Of course, if the article was true then using immutables and building objects wouldn't cause performance problems...

      Did I mention that Java serialization is also pretty slow in many cases? Luckily there are hooks so that you can perform custom externalization, which can speed up RMI.

      Don't trust me. Get some tools (OptimizeIt isn't bad, but also rely on measuring real throughput) and see where the bottlenecks in your code are.

      My apologies to readers for bothering to respond to the parent post. Moderate away (or do I mean moderate this away to -1, Redudant?).

    6. Re:The article is wrong by jdennett · · Score: 1

      Fair comment. I did not mean to say that JDO or similar persistence mechanisms are inherently slow -- just that they will be slow if you don't use them well.

      As with all synchronization, the key is to do as much as possible concurrently. That can mean batching updates, keeping writes restricted to small chunks of code, and so on.

    7. Re:The article is wrong by Anonymous Coward · · Score: 0

      There's almost certainly a very good quip in response to someone using the phrase 'if memory serves' in a comment about garbage collection, but it escapes me at the moment.

      ~Blake

  58. No proof and +5 Insightful? by Anonymous Coward · · Score: 0, Insightful

    I can just as easily pull some facts out of my ass. Jees, you java guys are thin skinned. I work with Java everyday and I agree with the original poster - it's fucking slow as hell to start. Grow up. After driving a supposedly turbo-charged 4 cylinder car for a couple of years I too began to think it was pretty fast - then I had the pleasure of driving an old V8 - no comparison. Be objective. Everything has its strengths and weaknesses. Java's libraries are its strength and its startup time and memory footprint is definitely a weakness.

    1. Re:No proof and +5 Insightful? by fredrik70 · · Score: 1

      yeah, but when you mostly use Java on the server side as servlets, beans, et. al. startup time is pretty irrelevant. THinking of which, it's not *that* slow IMHO... It's bearable... the java IDEs I use do more than well (and that's NetBeans and IntelliJ in case you wonder...)

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
  59. fp by Anonymous Coward · · Score: 0

    First postt!!!!!!1 -Support DeCSS, Nmap, crypto, and the RIAA

  60. Birdmen of Cornell University by Latent+Heat · · Score: 1
    Spreadsheets and browsers are one thing, but if Java is that good, we should be seeing it in "niche application" software.

    Research into bird songs has resulted in this project: http://birds.cornell.edu/brp/Raven/Raven.html.

    I tried it out: it is the dancing elephant; you tend not to focus on the quality of its dancing but on the fact that it dances at all. An oh yes, while the Raven UI is not exactly sluggish once it gets going, it takes ever so long to load on starup.

  61. Is it or isn't it? by KidSock · · Score: 1

    Just from reading the post description it left me wondering which urban legend they were going to disprove; that java isn't slow or that it really is after all.

    Seriously, saying "Java is slow" is not a very sophisticated viewpoint. Using String objects a lot is slow. The Swing UI is slow. This knocks out a lot of potential uses. No improvements in JVM technology are going to fix that I'm afraid. And .NET will have this problem too as will any language with a builtin String type and garbage collection.

    If you write Java like you write C it's not slow. If you're not doing constant string processing it's not slow. It depends.

    1. Re:Is it or isn't it? by Anonymous Coward · · Score: 0

      The "Swing is slow" idea is also an urban legend I'm afraid.

      While maybe not the fastest UI library around most performance problems with Swing are due to poor optimisation and programmer practice...

  62. 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.

    2. Re:Java not always slower by anshil · · Score: 1

      This IS an urban legend. Show some proof, and a *fair* test. The persomance tests I've that were written *for* java always were very unfair. Writing a stupid C program, and a very clever java program "showing" the java one runs faster. That with a little more hand optimization on the C code it runs faster too is discreet.

      --

      --
      Karma 50, and all I got was this lousy T-Shirt.
    3. Re:Java not always slower by anshil · · Score: 1

      Any *well* *written* C program will run at least as fast as a java application.
      (however stability and ease of development are the other arguments speaking for java)

      --

      --
      Karma 50, and all I got was this lousy T-Shirt.
    4. Re:Java not always slower by Anonymous Coward · · Score: 0

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


      It's true but your missing the point. There is very little memory management

      On my computer (XP1900) it tooks about 16s for the java version "1.4.1_02" and about 4Mo of memory to the system.
      About 21s for the gcc version 3.2 20020818 (cygwin) and about 1Mo of memory to the system

      I say "about" because figures can vary according cpu/motherboard/memory/OS, it's a relative measure, not mine is bigger than yours.

      So what, java is faster for repetitive static code, but the research on different JIT proove already that.

      A more "real world" fibonnaci program in object paragdim will look more like that and it took 2m18s and 5Mo of memory :
      int fib(int i) {
      Fib fib1,fib2;
      fib1 = new Fib();
      fib2 = new Fib();
      if(i<=2) return 1;
      else return fib1.fib(i-1)+fib2.fib(i-2);
      }


      Of course it will be completly stupid to code Fiboncci like that, just to show that the complexity of a program don't stop at the algorithm, but also to the underneath control of the ressource for a program to execute.

      This exemple is very simple, but in a real program you use a lot of object and very few static code.

      I'm not saying that Java can not be efficient in repetitive calculation, i said that this exemple is too much specific to be accurate.

      And the point is, perhaps java will perform better than C/C++ or the other way for intensive calculation, but you will not know unless you've got top class coders that rip out the gutt of the language in competition and produce the same program with the same input and the same output.

      Stick to the language wich fit you the best unless you are sure that a given language will give you a real edge for solving your problem.

    5. Re:Java not always slower by iGN97 · · Score: 1

      Interestingly enough, this is something C++ would do at constant time using template metaprogramming (that is, expand the fib(45)-call to the resulting value at compile time). So I guess the discussion would benefit from a real-life example. ;)

    6. Re:Java not always slower by cakoose · · Score: 1
      Any *well* *written* C program will run at least as fast as a java application.

      How did you come to that conclusion? The run-time profiling advantage can let the JIT do things like compile code with branch-prediction hints to make it run faster than a statically-run compiler could.

    7. Re:Java not always slower by Arandir · · Score: 1

      You're perpetuating another myth. The JIT will make the code go a heck of a lot faster. The example is a CPU point loop, and native code will of course be faster than byte code in this situation. Real-world Java applications are rarely able to benefit much from this however.

      As for it being faster than C++, that's a load of bull. Knowing how JIT/Java works and knowing how C++ works, I would expect identical performance. And fair demonstrations will show this. You need to use the SAME algorithm for both. No fair using an accumulating loop for Java and recursion for C++. No fair using the minimal language features you need for Java and using operator overloading and polymorphic classes for C++.

      I've always here this "urban legend" with regards to Java and C++. I've NEVER heard Java compared to C in this regard. Why? Anyone who knows C++ can tell you that a C++ program to calculate Fibonacci is going to be *identical* to the equivalent C program.

      So show me those two example programs using the exact same algorithms and using minimal language features.

      --
      A Government Is a Body of People, Usually Notably Ungoverned
    8. Re:Java not always slower by iGN97 · · Score: 1
      Consider this C++-program:
      #include <iostream>

      template <unsigned long N>
      struct Fib
      {
      enum { value = Fib<N-1>::value + Fib<N-2>::value };
      };

      template <>
      struct Fib<1>
      {
      enum { value = 1 };
      };

      template <>
      struct Fib<2>
      {
      enum { value = 1 };
      };

      int main() {
      std::cout << "Fib: " << Fib<45>::value << std::endl;
      }
      Now, we all know C++ template metaprogramming will kick both Java and C's ass, but look at these interesting numbers:
      larsde@debian:~$ time g++ -o fibmp fibmp.cpp -ftemplate-depth-100

      real 0m2.894s
      user 0m2.790s
      sys 0m0.110s
      larsde@debian:~$ time ./fibmp
      Fib: 1134903170

      real 0m0.024s
      user 0m0.010s
      sys 0m0.000s
      larsde@debian:~$ time ./fib
      Fib: 1134903170

      real 0m57.769s
      user 0m57.720s
      sys 0m0.000s
      larsde@debian:~$ time java fib
      Fib: 1134903170

      real 1m23.296s
      user 1m12.740s
      sys 0m0.100s
      larsde@debian:~$
      There are four different programs being run here; "fib", which is a C++-program compiled with icc (Intel's C++-compiler), it beats java slightly (gcc on the same program is beaten by java as you originally indicate).

      Running the fib-program takes ~58 seconds.

      Now, the "java fib"-program is your function with a class and a main-function, it completes in 1 minute 23 seconds (but still beats the gcc-version, which isn't listed).

      Now, for the interesting part: Running the compiled C++ metaprogram takes 0.024 seconds, which is not much, but still, it doesn't really do anything.

      But look at the time spent compiling the metaprogram (where the actual calculation of the fib is carried out);

      2.894seconds, which hands down beats both the C and Java-implementation.

      So the total time for calculating the fib(45)-call in C++ with template metaprogramming including compilation is ~3 seconds.

      Which indicates that the suggested way of doing it is so amazingly inefficient that one would save over a minute spawning g++ from Java using JNI.

      Draw your own conclusions. ;)
    9. Re:Java not always slower by pclminion · · Score: 1
      Try writing a simple recursive Fibonacci number calculator in both C++ and Java. The Java one is faster, when using a JIT enabled JVM.

      While I actually doubt this is true, I suppose that it could be true, if the JIT compiler is smart enough to figure out how to turn the recursion into iteration. Compilers already know how to identify tail recursion, and it isn't hard to imagine a JIT that can "see" that this function can be rewritten in iterative form. (g++ can't figure it out, but that doesn't mean it isn't possible). If you pitted a new JVM against an extremely old C++ compiler that can't optimize for crap, I think this could actually be true.

      On the other hand, a recursive Fibonacci function spends most of its time doing function calls, so it could just be that the (old, out of date) C++ compiler is producing very inefficient function calls compared to the JIT. But I have a hard time believing that one of the latest JITs can outperform one of the latest C++ compilers.

    10. Re:Java not always slower by anshil · · Score: 1

      A *well* *written* C application could even imitate this behaviour.

      I have never seen it's easy, but it can!

      --

      --
      Karma 50, and all I got was this lousy T-Shirt.
    11. Re:Java not always slower by Anonymous Coward · · Score: 0

      While I actually doubt this is true

      Why not try it and remove your doubt?

    12. Re:Java not always slower by bored · · Score: 1

      Ok, so i tried it on my dual 550 box and java is slower. What gives....



      ~ >time fibtest 45
      fib 45 is 1134903170
      70.19user 0.11system 1:10.94elapsed 99%CPU
      ~ >time java fibtest 45
      fib 45 is 1134903170
      111.58user 0.26system 1:52.77elapsed 99%CPU



      Both were compiled without any switches..



      This is more what I would expect, but maybe I did something wrong, instead of hard coding the number I passed it from the command line, where I convert it from the string to an int then pass it to your routine. After the recursive function returns I then convert the value back to a string and print it out.

    13. Re:Java not always slower by Procyon101 · · Score: 1

      Why recurse when you can phi?

  63. Intel's optimizing compiler helps it compete... by Futurepower(R) · · Score: 1


    Interesting.

    Intel's optimizing compiler helps it compete with other CPU manufacturers.

    Microsoft once sold a slow Pascal compiler. This doesn't seem to fit, but most of Microsoft's operating system sales are to computer manufacturers. This puts pressure on Microsoft to make its software as slow as customers will accept. Later Pascal compilers, by other vendors, were more than 10 times faster on the same machine.

    There is heavy competition in C++ compilers, so Microsoft's version is fast.

    What about VB? Is is fast? For most of its lifetime, I've heard that it is not. No competition.

    Probably the DEC hardware sales people were a dominant force in the company. I can think of a particular situation in which a company that was pushed to add a new VAX, when faster compiler output would have been better, and half the cost.

  64. rivals (sometimes exceeds) c/c++ by hlee · · Score: 1

    Performance analysis from this project to develop a high performance platform for internet services(http://www.eecs.harvard.edu/~mdw/proj/sed a/index.html) shows that Java can be better than c/c++.

    But in general, if your application involves a fair amount of I/O, the programming language isn't likely to affect performance all that much.

  65. Re:To what extent does this exist in other languag by One+Louder · · Score: 1
    Smalltalk certainly has this perception problem.

    What most people "know" about Smalltalk (slow, has reference counting garbage collection, requires too much memory) was arguably true 20 years ago, when it was truly pushing the envelope.

  66. Hey Java is slow for me. by Anonymous Coward · · Score: 0

    I write in C and asm so it is slow. Games programing when java can do quake3 without overloading the system I will be impressed.

    Basicly I want to see is java to binary ie Java classed to precomplied native binary(programs using all the time speed speed speed). Ie less runtime compling. Java and perl have about the same performace. C++ has never been a great bench mark as it is different on UNIX related and Microsoft.

    I will say it is slow until is show me that it can move with the speed I want.

    1. Re:Hey Java is slow for me. by Anonymous Coward · · Score: 0

      Well, good for you.

      When your customers experience a crash, they just curse and reboot.

      When IBM's Java customers experience a crash, tens or hundreds of millions of dollars are at stake.

      Games are trivia. Some of us work in the Real World, Neo.

  67. 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.

    1. Re:Why It's Still Slow, and What to Do by Oswald · · Score: 1

      I have always suspected that these things are true; you play to my prejudices, and so your message is well-received--almost epiphanous (really). But, to play devil's advocate, how do we explain languages like O'Caml which seem to produce code that is very very close in speed to tha written in C? Is this only true in toy programs?

    2. Re:Why It's Still Slow, and What to Do by Markus+Registrada · · Score: 1
      Sagely, Oswald asks, "how do we explain languages like O'Caml?"

      Or certain Lisp implementations, likewise. There are several answers to this.

      First, when performance matters, O'Caml and Lisp are typically compiled not to bytecodes, but to native code. They can often be optimized rather better than C or C++ because they do not cater to pointer abuses, and because their compilers are written in a language better suited to writing optimizers than C is. Thus, there's no analog to the typical JVM problems of data and code pages unshareable among processes, and no cache pressure from a JIT compiler or its instrumentation and redundant code representations, and some overhead may be played off against better optimization.

      Second, I gather that O'Caml makes it easier to avoid abusing GCed memory, so you can often ensure that inner loops don't generate garbage and end up with allocations walking the address space. (Disclaimer: I haven't used O'Caml industrially.)

      Third, it is very easy, when writing O'Caml or Lisp, to run afoul of the same GC problems. Thus, serious programs written in O'Caml, such as Unison, must have had special attention paid to avoiding GC-induced problems. The QPX airline fare search system, written in Common Lisp and used on Orbitz and Continental Airlines sites -- perhaps the most heavily used industrial Lisp application in existence -- never GCs. It calls out to a huge C++ library for anything that needs dynamic allocation or floating-point operations.

      It's possible to make Java programs go fast, it's just very hard. Compile them to native code with GCJ, turn off runtime checks, and keep the garbage collector and anything that generates garbage under a gimlet eye, and you may get performance comparable to C++. I happen to find it more satisfying to write in C++. Maybe I care more about performance than most, and prefer to work on programs where it matters more. When performance and type-safety don't matter much, I use Python.

    3. Re:Why It's Still Slow, and What to Do by sjames · · Score: 1

      Cache is no great mystery other than the complexity of figuring out when shrinking things by a single byte will vastly improve performance by avoiding cache invalidation in a tight loop. In general, the best thing to do in the cache is keep loops tight, then try unrolling them to varying degrees until you find the fastest run. Unfortunatly, VMs and JIT compilers generally don't do that.

      In memory management, keep it tight and try to keep long term allocations together and ephemeral ones shouldn't share a page. Keep metadata seperate and use madvise (where available) to throw pages away without swapping them back in. Unfortunatly, most VMs apparently don't do that either, and to the best of my knowledge, there is no way to provide hints to the allocators. It might be nice to have advisory destroy functionality so that memory can be explicitly released and the GC becomes a catchall for cases where destroy isn't called. There's probably more, but I've only half finished my coffee this morning.

      Of course, the above would return responsability to the programmer and offer no protection from dereferencing a destroyed object, so it probably won't happen.

  68. 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.

  69. 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).

    1. Re:Java 1.4+ *does* have non-blocking IO. by glenebob · · Score: 1

      select() is very decidely a blocking call. It enables you to avoid blocking IO calls, and provides a timeout mechanism, but it certainly blocks.

      I've never seen an async or non-blocking API that's as simple and straight forward to use as select(). If your thread does other things besides just IO, you may be forced to use non-blocking calls, but when you can get away with it, select() is sweet.

    2. Re:Java 1.4+ *does* have non-blocking IO. by mgrant · · Score: 1

      Good point--there's a distinction between multiplexed IO and asynchronous IO, and select() is definitely the former.

      I think a lot of people (myself included) tend to use the term non-blocking IO loosely to mean both async and multiplexed IO, the rationale being that both strategies allow you avoid having your main thread of execution block indefinitely on an IO call. But you are right in pointing out that select is a synchronous call, and you certainly can make select() block indefinitely by not specifying a timeout.

      I think we're on the same page here... I'm probably just abusing the term ``non-blocking IO.''

    3. Re:Java 1.4+ *does* have non-blocking IO. by fizbin · · Score: 1

      I've never seen an async or non-blocking API that's as simple and straight forward to use as select()

      VMS's QIO subsystem was pretty sweet in this regard, and the TGV network stack made it easy to use QIO with TCP connections.

      Of course, if you were using C your life was painful in general on VMS, as you were constantly reminded over and over again the different ways in which VMS was not unix, but if you were working in a more VMS-friendly language (like DECPascal) QIO rocked.

  70. Bzzzt by Imperator · · Score: 1

    Wrong answer, but thanks for playing.

    True interpreted languages are slow. When you write a script for bash, it's read in line-by-line and parsed each time you run the script. (But it's also slow because you typically are creating lots of different processes, which is why being interpreted is the last performance problem you should worry about in shell scripting.)

    Java is not interpreted. Java is compiled. Whether the format to which it is compiled is native for your processor or not is an entirely different question. Java (similar to Perl under mod_perl or other schemes) emulates an idealized Java processor, but it does not interpret it. This is much faster that interpreting a language.

    Those of you who used the first PowerPC-based Macs have experienced the difference. Almost all the applications you ran were compiled for m68k, but Apple had a software m68k emulator that ran them several orders of magnitude faster than if your 601 had been interpreting the C (or often Pascal) sources.

    The reasons languages like BASIC or Perl (regardless of whether they are interpreted or compiled/emulated) tend to be slower than languages like C and Java are:

    1. their interpreters/compilers tend to suck at optimizations compared to, say, a good C compiler; and
    2. they hide at the language or library level many things which make programming faster but bloat the code path (e.g. using dynamically sized arrays even when the programmer knows how much he'd like to allocate).
    --

    Gates' Law: Every 18 months, the speed of software halves.
  71. Simple solutions by Imperator · · Score: 1
    • Use less memory
      • Use fewer threads
      • Use mutable objects
      • Use proper OO so you don't have to create objects with data members that are irrelevant to the task you want
    • Buy more memory
    • Call System.gc() periodically (preferable after finishing with a batch of objects and before allocating the next batch)

    Again, if you really need to have everything in memory at the same time, get more memory. Or just learn to trust your OS's memory manager to page for you.

    --

    Gates' Law: Every 18 months, the speed of software halves.
  72. ThinkFree Office and lots of IDEs... by Anonymous Coward · · Score: 0

    ThinkFree Office is a set of office applications that uses Java. I nevered played with it, but apparently it's not bad. Also, there are tons of IDEs out there that uses Java and works quite well. My personal favorite is IntelliJ. I use it on OS X, and granted, it's not as fast as Carbon/Cocoa apps, but its performance is quite decent on my 667MHz PowerBook, and I can imagine with a newer machine it would be even more acceptable.

  73. Re:Immutable objects do NOT suck. by Anonymous Coward · · Score: 0

    Read the article. It thoroughly explains why you're wrong.

  74. I'm sooooo sure Freenet isn't the problem by Anonymous Coward · · Score: 0

    That sounds more like an issue with FreeNet than anything else. If anything, you sound like you'd be more interested in the memory footprint of a "Hello, World".

    It ain't 70MB.

    1. Re:I'm sooooo sure Freenet isn't the problem by Anonymous Coward · · Score: 0

      Actually, "Hello, World" uses about 12 megs...

  75. 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 Anonymous Coward · · Score: 0

      "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."

      Try to reply to what your parent said. Sure, program design techniques and paradigms are independant of language, but when you're faced with hard speed requirements, your choices are limited.

      Java is fast enough for most applications but is absolutely horrible for small internal command-line tools where dev time is delta and efficiency is paramount.

    3. Re:Sure I remember... by james_bray · · Score: 1

      "Java and VB just turn things into manufactured housing"

      Please dont place Java and VB in the same category. Java has been designed from the ground up as a modern object oriented language; VB is a hacked mess that has "evolved" into what is currently is.

      --
      http://www.reeb.freeserve.co.uk
    4. Re:Sure I remember... by Anonymous Coward · · Score: 0
      Not all programs have the same requirements. In most cases developer time is much more valuable than CPU time.

      I wonder why people keep saying that in this Open Source age. OS has proven that developer time is not expensive. As more and more source code will be open, this argument will quickly become moot.

      Very amusing also is the way java zealots argument about the JIT: JIT is faster than static compiles! Sure the program runs slower when you start it so it all depends on how long it runs, but JIT is faster anyway because you don't write short-running programs in java! Believe me! These are not urban legends!

    5. Re:Sure I remember... by wakebrdr · · Score: 1

      What the other responder said about "developer time is much more valuable than CPU time" deserves more comment.

      Yes, I'm sure you're an alpha coder. I'm sure you demand a helluva salary. And I'm also sure that coders of your caliber are a small subset of all coders available in the labor pool. So how would a manager ensure that their programming project didn't blow up at runtime? Let's see.....they could get into a bidding war with lots of other managers at other companies for your services, or they could implement their project in a safer but slightly slower language: Java.

      It's a simple business decision.

      --
      Slashdot: Liberal News for Nerds. Liberal Stuff that Matters.
    6. Re:Sure I remember... by rnd() · · Score: 1

      Correction: A console-based Hello World program in VB.NET creates a 6.5KB executable.

      --

      Amazing magic tricks

    7. Re:Sure I remember... by rmdyer · · Score: 1

      Sure, I know that. Tiny little executables get produced for Java too. The problem is the thing won't run without the runtime libraries loaded, which turn out to be very large. The VB virtual machine for VB6.0 is 1384448 bytes for example. That's just for the core language. This doesn't count all the custom control OCX's and other stuff your program might use. With VB.NET, your program won't run without the .NET Framework installed (what is that, around 25Meg ?). Try sending a 6.5k program to someone who doesn't have the required libraries and see what your get.

      In the early days, before Java, there was talk about how Microsoft couldn't include the VB runtime libraries into the core OS install. Many VB programmers wanted this so they could just distribute tiny little apps. The problem was, and probably still is, that including those libraries would necessarily mean they would have to include libraries from other companies who write languages. VB is a language and a product from Microsoft. You can't allow the languages product line from Microsoft to have any advantage in the industry by including only their runtime libraries into the core OS.

      Try running that 6.5k app, then look at the task manager to see how big a memory footprint it uses. Make sure you modify the task manager to show all the columns that include physical and VM size.

      +1.0

    8. Re:Sure I remember... by gregmac · · Score: 1
      I wonder why people keep saying that in this Open Source age. OS has proven that developer time is not expensive. As more and more source code will be open, this argument will quickly become moot.

      Hmm. BigAccountingCompany Inc needs some software that allows them to handle one of their specific business processes. So, they go out to the open source community and say "hey, would someone please make this program for us?" and proceed to publish the details of their business process.

      In a 'perfect' OS world, a bunch of developers that have some spare time would gladly take up this offer and help BigAccountingCompany Inc out. And none of their competitors would look at the business process details because that would just be cheating.

      I don't think I have to tell you what kind of world we actually live in..

      So what really happens? BigAccountingCompany Inc hires a consulting company to in, and at at very high hourly rate, they sign an NDA saying they'll keep the details of the process and any programs created confidential, and write the software.

      This development time IS NOT cheap, and can not be sourced out to the OSS community.

      Of course, maybe we do live in a perfect world. When was the last time you volunteered your time towards helping out a company with a program that will be totally irrevelant to you?

      --
      Speak before you think
    9. Re:Sure I remember... by Anonymous Coward · · Score: 0

      Maybe, if you ignore the runtime libraries.

      Hello World in Java compiles to a 417 byte file.

      That's right, 417 bytes.

    10. 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.

    11. Re:Sure I remember... by rnd() · · Score: 1

      How is this any different from needing to include stdio.h when writing hello world in c?

      Sure, the .net runtime may be a bit bigger than the standard c libraries, but it does a heck of a lot more.

      BTW, vb.net and c# were not really designed to create a hello world with a small memory footprint. In fact, no OO language would really be ideal for that.

      Programming shoudl be done as far removed from the hardware layer as possible, so that it is generic and portable. Sure there are some people who can hand-optimize code for a particular architecture, but that takes time and diminishes portability. Also, those people are the minority. In most cases, the compiler does a much better job of machine level optimization than the programmer.

      For many projects, it makes sense to use a high level langauge so that the semantics of the application can be clearly defined, and the application is actually a model of the problem it is intended to solve. It is generally harder to do this when you're worrying about a lot of machine level details.

      The above paragraph is a statement about design. If that application doesn't perform well enough, then a business decision must be made: Does it make more sense to add hardware or to rewrite portions of the application in a lower-level language in order to eek out a bit more performance?

      Perhaps your needs do require coding in c for your command line utilities. I think it's a bit of a stretch to extrapolate from that that all high level languages suck.

      BTW, if you are running n copies of that hello world app in vb.net, your machine will only need to load one copy of the .net runtime to handle all of them.

      --

      Amazing magic tricks

    12. Re:Sure I remember... by Ajatollah · · Score: 1

      Acctually I humbly believe that rmdyer has a very important point in his/her position, programming is in fact something that should be done with some grade of skill, or at least knowledge, Java has its virtues, (from my point of view) in the conceptual realm, it has this all kind of little nice details of the object oriented paradigm, and somehow manages do detach itself from the implementations of the system it will be running on. This is good for a programmer, as many people have pointed here it allows the programmer to concentrate and move it's techniques from one platform to another with relative ease, but this comes at a heavy cost. For all people that just don't get it: JAVA IS SLOW, Either in start up, execution or the price we pay in memory footprint, trying to deny it, is just foolish. JAVA is good at least in a sense, but the fact is that we (as developers) keep a somehow anoying tendence to look away from the truth. Java as many other development platforms of these days are far from good performing, Ghz cpus, cheap memory give us the funny illusion that things run well. But if any of you has some memory of what computing was 10 years ago, it's easy to see where are we going., today we have 20 to 30 times faster systems sitting in our desktops, with them we can develop, debug and even test these modern programs. But as I see it, these programs are not 20 to 30 times much more functional as we might expect from these systems, maybe my memories does not want to let go such days, but running a clearly slow program in a modern day computer should be a shame it means it needs 20 to 30 of those 10 years ago computers power to do what? 1.7 times what we did on one singe computer of that time? these are magic numbers I pulled out of my underwear, and I have no solid base to state what I'm stating, but if you give it a little thinking you will know it's not so far away from truth. Large scale aplications of course are difficult to do on low level paradigms, but we better be careful and do not lose sight of what is the systems we are developing are intended for, because we might end up just programming those 'hello world' programs in java or .net. I'd not use these unless the size of the system at hand would require so. New platforms allow for larger scale development, but it'd be foolish to think it can replace good old programming for every programming task. And yes, regular Bussiness manager does know little about speed or bytecode performance, all they see is the result, either it works or it doesn't for their needs, but why should we let such ignorance drive the direction that the thechnologies take? If we have good tools for a task we should use them and not jump in a bloated bandwagon just because market forces dictate so. Again sorry for the crappy english.

    13. Re:Sure I remember... by Anonymous Coward · · Score: 0

      I fail to see what it is about a language that basically copies C++ that constitutes "built from the ground up." Java is painfully slow compared to C, that's a fact. There is so much overhead that it's not funny. The idea that CPU usage is "free" probably helped contribute to the .com bust. If you're not smart enough to handle pointers, or checking for array index out of bounds problems, or operator overloading, then you shouldn't be programming.

    14. Re:Sure I remember... by james_bray · · Score: 1

      "I fail to see what it is about a language that basically copies C++ that constitutes 'built from the ground up.' "

      Actually, Java is more closely related to SmallTalk than C++. The syntax is borrowed, the semantics are not. Subtle, but important difference.

      James Bray

      --
      http://www.reeb.freeserve.co.uk
    15. 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.

  76. Sucks not to be an apple user by davesag · · Score: 1
    For now it just sucks not to be an Apple user.

    I can only imagine it's always sucked not to be an apple user. the apple ][ was awesome.

    --
    I used to have a better sig than this, but I got tired of it
  77. 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.

  78. Hey dumbass by delmoi · · Score: 1

    That memmo was written in 1999

    --

    ReadThe ReflectionEngine, a cyberpunk style n
    1. Re:Hey dumbass by axxackall · · Score: 1
      And what's changed since then? Nothing. I am working with both Java and Python no both GUI-client and web-server sides since all these year and I can tell: all proportions between Java and Python hasn't been changed. JVM is still big, it starts slow, it has huge memory leaks and it breaks compatibility every minor release. Python interpreter starts fast and it's small.

      But don't even think about starting a flame war: I will talk only to people who has production-quality experience with both Java and Python.

      There are few cases where you would prefer Java. In the rest of application Python is more appropriate. The major benefit java has got all these years is Sun, IBM and others who are eager for profit and who is ready to do everything for that. That's why they are aggresively pushing Java to the market. It was easy for them as most of IT/SE managers blindly accepted everything from advertisement.

      1999? It's even proves more: since that time Sun hasn't changed anything to improve the situation. Why. B/c they didn't have to. No need to invest money to engineering department in order to improve Java if marketing department works much better. All they added for these years were features good for marketing.

      At the same time, these years, Python has been improved a lot targeting the quality of python-based application: the language, the interpreter performance and it's stability. Without any commercial push, Python is coming more and more popular. For me - the best ad is no ad but still sucess.

      --

      Less is more !
  79. 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.
  80. 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.

  81. come the fuck on by Anonymous Coward · · Score: 0

    IBM's current buisness strategy depends on Java. They're about the last people to 'set anything straight' about Java. They'll happily tell you that Java is perfect for your every need and that it will give you a blowjob too.

    Could you not imply that the most biased source is unbiased? Jesus Christ! Next thing you know you'll have unbiases appraisals of Linux by Linus and Stephen King's new review of his own new book.

  82. 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.

    1. Re:It is a trade-off by Anonymous Coward · · Score: 0

      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

      Actually, good garbage collectors generally cause less overhead than manual memory management, because memory tends to be deallocated in smaller chunks (i.e. less pauses).

  83. Even better performance on the horizon by Trinition · · Score: 1
    Two things I'm looking forward to in upcoming versions of Java:

    • Multi-process JVM (share the VM memory overhead!)
    • Templates (avoid unnecessary runtime casts)
    1. Re:Even better performance on the horizon by truth_revealed · · Score: 1

      The Speedy Java VM Mantra
      (aka "Tomorrow" Lyrics © Martin) Charnin

      The sun'll come out
      Tomorrow
      Bet your bottom dollar
      That tomorrow
      There'll be sun!

      Just thinkin' about
      Tomorrow
      Clears away the cobwebs,
      And the sorrow
      'Til there's none!

      When I'm stuck with a day
      That's gray,
      And lonely,
      I just stick out my chin
      And Grin,
      And Say,
      Oh

      The sun'll come out
      Tomorrow
      So ya gotta hang on
      'til tomorrow
      Come what may

      Tomorrow!
      Tomorrow!
      I love ya
      Tomorrow!

      You're always
      A day
      A way!

    2. Re:Even better performance on the horizon by Anonymous Coward · · Score: 0

      Another thing I am looking for in future versions of Java:

      Drop the silly static typing that requires casts and/or templates in the first place.

      Static typing is for wimps. Real programmers do it at runtime.

      A thorough knowledge of strong typing is required to write functioning programs. Learning a statically typed language in your first term helps. After that, static typing is only a crutch that allows people to program who probably should not; they do not have the necessary mindset.

      Just my 2% of your favourite currency unit.

    3. Re:Even better performance on the horizon by cakoose · · Score: 1

      Static typing is such a pervasive part of Java you might as well use something else (like Ruby or Python). What does Java minus static typing have that you can't get from somewhere else?

  84. Best Tip: Think First by Anonymous Coward · · Score: 0

    This is exactly the kind of advice where you end up trying to optimize a bubble sort. No wonder you posted this as an AC. :)

  85. 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

  86. using the final keyword by FuzzBucket · · Score: 1

    I disagree with the author's advice discouraging the use of final classes and methods. Both from a design and a performance method, I think final classes and methods are underutilized by programmers. For an in-depth essay on why, see here.

    1. Re:using the final keyword by qon · · Score: 1
      Couldn't disagree more. Java may fail to specify firm contracts regarding internal class method dependencies, but final is no way to address this problem. Your solution solves a potential problem with method overriding, but at the cost of creating a whole bunch of other intractable problems, such as not being able to specialize a class at all! A very arrogant thing for a coder to disallow.


      For an in-depth essay on why final really does suck, see here.


      Q

  87. your reading skills are lacking... by slittle · · Score: 1
    Because MySQL tables are stored as files, it is easy to do a backup. To get a consistent backup, do a LOCK TABLES on the relevant tables followed by FLUSH TABLES for the tables. [deleted page specs] You only need a read lock; this allows other threads to continue to query the tables while you are making a copy of the files in the database directory. The FLUSH TABLE is needed to ensure that the all active index pages is written to disk before you start the backup.

    That you must lock the tables to back up while they are being backed up is a bad thing. The requirement to do a FLUSH TABLES, although less egregious, is still a little suspect. I do not recall having to flush indexes in Sybase, Oracle, or PostgreSQL before doing a full database backup.

    This is a FILE LEVEL backup - you have to flush the daemon's write cache back to disk.

    While MySQL allows you to simply block updates temporarily, PostgreSQL says you must SHUT THE DATABASE DOWN COMPLETELY (http://www.postgresql.org/docs/view.php?version=7 .3&idoc=1&file=backup-file.html) to do a FILE-LEVEL backup.
    --
    Opportunity knocks. Karma hunts you down.
  88. 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.

  89. hmm? by Trepidity · · Score: 1

    Reference counting is most certainly sub-optimal for a great many situations.

    1. Re:hmm? by pyrrho · · Score: 1

      you need to specify the criteria. I can think of cases where it's suboptimal for the sun to shine, but it's pretty contrived and special case.

      I especially predict that in managing memory that is shared by different client modules you will at LEAST have to reference count. If you need more, then you reference counting alone is not sufficient. If you do not need more, it is sufficient, and it is optimal.

      I can think of times you would not want to reference count, but it's not because there is any more optimal solution to tracking references! (more like you don't want to share memory or you know you are not going to free the relevant memory anyway)

      --

      -pyrrho

  90. Re:To what extent does this exist in other languag by Anonymous Coward · · Score: 0

    Use a profiler. It will tell you exactly where your bottlenecks are.

    When I first started using the STL my instincts told me "this much functionality must come at a heavy price" but when I profiled my code, the STL map was way way way down there on CPU usage.

    The old myth that floating point operations are slower than integer is wrong too. We tested that one 5 years ago and a floating point operation of the same values often beat the integer operation.

    Exceptions are often decried for being slow, but, if you profile code you find that function calls 3 levels deep or more are SLOWER if you check error returns at each level that if you have a catch clause. This test was done with the Visual C++ compiler version 6.0

    This was all done on Pentium class chip.

    Strange.

  91. Re:To what extent does this exist in other languag by Anonymous Coward · · Score: 0

    Java has a profiler built into the JVM, and if you want a prettier interface with real-time analysis options (Like watching object counts as they're created and destroyed, etc) then you can buy one of any number of commercial profilers.

  92. micro-benchmarks irrelevant by alienmole · · Score: 1

    It's possible that on some micro-benchmarks like the one you mention, Java with JIT might outperform some other languages on some edge cases. But for real systems, Java is slower. I've more than once had to port Java systems to other languages for no other reason than speed - and the speed improvements have been dramatic. One big issue seems to be that method dispatch in Java can be relatively slow. And since everything's a method...

  93. Re:Sucks not to be an apple user (pre/post NeXT) by kwerle · · Score: 1

    There was about a decade when I wouldn't touch a mac. And I have no regrets at all about that. From 86-98, or so. In 88 the NeXT came out, and MacOS was stuck in single user, no protected memory, no multitasking.
    What a piece of crap.
    I had absolutely no respect for the platform. I saw the NeXT glossies and was totally in love. I mean... Unix, Display Postscript, OOP; it was the only platform to own.

    But I'm biased, as you can see from my resume' at my website.

  94. Re:My favorite by TheRaven64 · · Score: 1
    But, another good one was the time that wrote a java application that made my web browser not slow to a crawl.

    Umm, Java applications don't run in web browsers...

    --
    I am TheRaven on Soylent News
  95. funny... by rmdyer · · Score: 1

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

    This is a funny thing to say. I think end-user time (and resources) is much more valuable than developer time! That is why they are paying for your progam in the first place.

    You said..."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."

    You should be surprised. Sure, techniques are independent of language. I may have been wrong to use the word skillz. More precisely, part of being skilled at something is experience. Experience in one language does not directly translate to another very easily. Verbal languages that people speak around the world is an example. The syntax and constructs might carry over easily, but learning what all those words mean (or do, as in the case of programming languages) can be hard.

    I can't justify telling everyone to use C all the time. Of course, every problem has a specific solution that works best. You are correct, there is a trade-off. I'm just saying that, over time, you may regret not knowing something well that is, in fact, more efficient and effective for writing compace and fast code. I sort of regret all the programming time I threw away with VB. But, I still use it when push comes to shove, and I guess I should be happy I know a good bit about the language. Being versatile is good, but being a jack of all trades, master of none, sucks!

    +4 cent.

    1. Re:funny... by Anonymous Coward · · Score: 0

      That is why they are paying for your progam in the first place.

      Yes. The end users are also PAYING FOR THE DEVELOPMENT TIME.

      If the choice is between hiring a programmer for a day to produce something that runs in 1 second, or hiring a programmer for a week to produce something that runs in 0.5 seconds (and is full of security holes that require constant expensive maintenence in the bargain), most customers will opt for the 1 second run time, especially if they're only running it once or twice a day.

      In a modern PC, the vast majority of CPU resources are idle most of the time. Most of the time, the CPU is sitting there waiting for you to press a key.

      It's a tradeoff.

  96. Here's one by qon · · Score: 1
    Here's one. Check out Semantica by Semantic Research. These tools let you create, edit and view semantic networks, and they're all written in 100% pure Java. Download Semantica Reader 3.0 (beta) if you want to give it a spin.


    Q

  97. Um... not quite by qon · · Score: 1


    Java just isn't popular on the desktop, because you never know what crazy JVM version someone's going to have on their system.


    Wrong. Java applications can be distributed with their own private JVMs. Check out InstallAnywhere for more details.


    Q

  98. Easily de-compiled and slow makes more money. by Futurepower(R) · · Score: 1


    Joel Spolsky was theorizing about Sun in what he calls Strategy Letter V. (See the bottom for the paragraphs about Sun.) He wondered why Sun wants Java, and he was not able to guess.

    Here is a theory: Sun wants its own software to be secure and fast. However, there is a conflict of interest. Sun makes more money if its customer's software is easily de-compiled. If Sun sales people find one customer doing particularly well, it is easy for Sun's other customers to de-compile the original customer's Java code and re-write it to work for their own purposes. This would benefit Sun because the salesmen could more readily sell the hardware that runs the Java program. Slow and easily decompiled makes more money for Sun.

    Did I make enough jokes in my parent comment about Java being slow? They should rename Java and call it InsultMe. Most of the time when I see a Java program, it is so slow and the GUI is so quirky that I feel insulted that someone expects me to think it is acceptable.

  99. The problem is most programmers are ignorant by Anonymous Coward · · Score: 0

    Most programmers are ignorant of how to create simple performance tests in order to verify urban legends for themselves. This includes a lot of open-sourcers and IRC lurkers as well.

    Professional (not most) programmers and project managers can't afford such ignorance. We test things, and build our opinions on fact rather than heresay. New programmers should consider the difference between heresay and experiment.

    Java performance urban legends are low-hanging fruit -- easily debunked. Anyone who propagates these sorts of rumors clearly doesn't have the experience to construct valid tests. But testers who have bothered to check are rewarded with knowledge that will let them use a very uniform language without fear of architecture-imposed performance problems.

    Such knowledge is freedom from worry, to a programmer.

  100. Double-Checked Locking by KDan · · Score: 1
    It was the fear of this very myth that inspired developers and writers to promote the clever-seeming, but fatally flawed "double-checked locking" idiom, which appears to eliminate synchronization from a common code path, but in fact compromises the thread-safety of your code.

    How does double-checked locking compromise the thread safety? It doesn't at all. That's bullshit. Double checked locking is perfectly safe. Example:

    public MyClass getInstance() {
    if (this.instance == null) {
    synchronized (this.getClass()) {
    if (this.instance == null) {
    this.instance = new MyClass();
    return this.instance;
    }
    }
    }
    return this.instance;
    }
    The above code is perfectly thread safe, but avoids having to run synchronized code at all once the object has been created. Whether the overhead is noticeable is debatable, but the double-checked-locking pattern is thread-safe.

    Daniel
    --
    Carpe Diem
    1. Re:Double-Checked Locking by Animats · · Score: 1
      OK, students, as an exercise, find the race condition in the above code.

      Hint: Is assignment guaranteed to be an atomic operation? Discuss.

    2. Re:Double-Checked Locking by KDan · · Score: 1

      The assignment is synchronized. So in the context of this class and this method, it is guaranteed to be atomic as far as all other threads running this method can see. No two threads will be able to synchronize on this method at the same time. By the time the first thread is finished, the object is allocated. So by the time the second thread gets to the second check (hence double-checked locking) the object is already assigned so the check fails and the existing instance is returned. It is fully thread-safe.

      Daniel

      --
      Carpe Diem
    3. Re:Double-Checked Locking by Anonymous Coward · · Score: 0

      This is not thread safe, do a google search on double checked locking and java.

    4. Re:Double-Checked Locking by Animats · · Score: 1
      No, no. Being synchronized only affects other threads inside the same synchronized context. Unsynchronized threads aren't blocked. They don't check for the lock. Where would they block?

      Anything that uses native threads in the JVM is vulnerable to this problem. On single-CPU machines, it's unlikely, but on multiprocessors, it can happen much more often. Note that "hyper-threading" CPUs are multiprocessors for locking purposes.

    5. 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).

    6. Re:Double-Checked Locking by KDan · · Score: 1

      Wow, ok. Fair enough... thanks for the informative article. That's pretty shitty of sun to have screwed around with the definition of synchronized like that. Surely such an important point should be well highlighted in the courses for the Sun Certification (the SCJP anyway). Instead, there, they basically say that synchronized makes the instructions it surrounds atomic with respect to any other threads that are synchronized to the same object. If there are these reordering issues it means that probably about 2/3rds of the 'thread-safe' programming out there is actually thread-unsafe on hyperthreading cpus, multi-cpus and optimizing compilers... Pretty bad shit.

      Daniel

      --
      Carpe Diem
    7. Re:Double-Checked Locking by cakoose · · Score: 1

      I don't understand...are you saying that two threads can be executing code within the synchronized block at the same time? What is an "unsynchronized thread"?

    8. Re:Double-Checked Locking by Animats · · Score: 1

      This is covered far better in the "double-checked locking declaration" cited above.

    9. Re:Double-Checked Locking by KDan · · Score: 1

      Hrm...

      The more I think about this issue, the more it bugs me. It seems to me that with this additional information thread-safe programming using synchronized blocks (rather than methods) becomes an extremely complex issue in Java... If things don't happen sequentially, how can there be any programming at all??? It seems to me that requiring that what you write on line 10 happens after what you write on line 9 is as basic as requiring that cause happens before effect - if you turn the latter on its head, all physics goes *poof*. If you turn the former, I would say that programming languages also go *poof*.

      This is bothering me seriously... anyone got some light to shed on this?

      Daniel

      --
      Carpe Diem
    10. Re:Double-Checked Locking by Anonymous Coward · · Score: 0

      as a programmer with plenty of multithreading experience on CPUs which do all of the above, heres what you do to get java code thread safe :
      use atomic spinlocks in synchronized function blocks with a dekkers algorithm to control the whole shebang.

    11. Re:Double-Checked Locking by KDan · · Score: 1

      Hum... You mind posting some links with more information on "atomic spinlocks" and the "dekkers algorithm"?

      Daniel

      --
      Carpe Diem
    12. Re:Double-Checked Locking by kinga · · Score: 1
      Oh, you're still reading. I don't think my mail to you went through (from your website), PHP threw some sort of error.

      Anyway, since the AC isn't here I'll explain a spinlock. Basically, you try to write a value into a word using an atomic compare and exchange (xchgl on x86). If the write fails, you loop (spin) for a very short time and the try again. You can also timeout if you the write keeps failing. In pseudo-code:

      while (atomic write fails) { sleep a little; tries++; if (tries > too many) { give up; } }

      I can certainly send you some code for doing this with C on x86/SPARC, but I'm lost as to how to do this (efficiently and correctly) in Java.

      As for Dekkers, I remember doing that in OS but cannot find a decent reference to it other than the stuff that shows up on google.

  101. 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.

    1. Re:Simple code is more future-proof by KDan · · Score: 1

      Yes, but if you're programming something really speed-sensitive (eg a game) you can't afford this. It's excellent practice for web applications and desktop applications that need to be maintainable first and fast second. But if you're programming a game engine and you need to squeeze every bit of speed out (as you do when you are programming games) you'll want to use every trick available, even if it might not be useful later - it's useful with the compiler you're using now!

      Daniel

      --
      Carpe Diem
    2. Re:Simple code is more future-proof by adamsc · · Score: 1

      I think that's a difference in goals - game engines are an example of code you don't really expect to maintain in the normal sense. A game engine which is 5 years old is dead from a commercial standpoint - in contrast, much of the business world still relies on COBOL modules which were first written 20+ years ago.

      Game programmers can also assume a higher level of competency for the reasons you mention - someone who is confused by pointer arithmetic is probably not going to be very useful on projects with such tight performance goals and delivery schedules.

      (The usual caveats about premature optimization also apply but I don't have anything to say there which hasn't been rehashed countless times before)

    3. Re:Simple code is more future-proof by fredrik70 · · Score: 1

      um, what's so much harder about grasping about a pointer increment than array indexing?
      Also, how do one optimise a jump in memory more then as a jump in memory? (I suppose I should go back and check the first geezers source)

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
    4. Re:Simple code is more future-proof by adamsc · · Score: 1
      um, what's so much harder about grasping about a pointer increment than array indexing?


      Obviousness - which one will seem obvious to an inexperienced programmer like, say, a hypothetical trainee given the task of making minor changes to an old program.

      Also, how do one optimise a jump in memory more then as a jump in memory?


      You can't. The optimization comes from realizing that you're frequently performing the exact same operation on many elements and could thus use multiple threads and/or SIMD to parallelize it. Pointer math doesn't imply that this is the case so you're hoping that the compiler is smart enough to recognize that you are performing a parallelizable job. There's also an entire class of optimization problems facing a compiler attempting to determine if a given block of C can be parallelized safely, given certain uncommon but legal uses for pointers.
    5. Re:Simple code is more future-proof by fredrik70 · · Score: 1
      Obviousness - which one will seem obvious to an inexperienced programmer like, say, a hypothetical trainee given the task of making minor changes to an old program.

      Must say I believe pointer arithmetic is such an integral and common part of c that it is one of those things you, as a programmer, must grasp. I cannot really see how it is less obvious than indexing, it's just another way of expressing what you want to (gettingthe next item in an array)


      The optimization comes from realizing that you're frequently performing the exact same operation on many elements and could thus use multiple threads and/or SIMD to parallelize it

      Ah, clever! never though of that.

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
  102. Sub Selects anyone???? by keepper · · Score: 1

    You must be freking kidding right...? Sub-selects
    and a working optimized join are still missing
    from MySQL..

    ( and don't talk about the upcoming 4.X version...

    It's still not copletely ready...

    These are critical features needed in most apps..
    and having to do shity work arounds is not the way )

    1. Re:Sub Selects anyone???? by LDoggg_ · · Score: 1

      Also, Sequences and Views.

      Postgres and Oracle, and many others have these.

      --

      "If they have both, tell them we use Linux. And if they have that, tell them the computers are down." -Dave Chapelle
  103. Java is slow. by master_p · · Score: 1

    Ok, what the guy says is correct, except for the fact that more temporary objects allocated on the heap don't matter on performance.

    But, Java is still slow. Slower than other languages. Let me give you some examples:

    1) there is still no Java-based office application suite (and even if there is one, it is surely not widely known). You know why ? Because Java is slow.

    2) I recently tried to use Poseidon for UML design. It is written entirely in Java. When the diagrams got a little big, Poseidon was way too slow.

    3) I've got JBuilder 4.0 on my home Athlon 650 MHz/650 MB RAM and it is slow to the point of being unusable. Ok, that's an old product but...

    4) in work I've used JDeveloper 9 from Oracle. Latest edition. Very slow, to the point of being annoying.

    All of this under Windows. Half of the blame goes to the developers, I am sure, because they did not try to optimize their algorithms/formats/whatever. Half of the blame though goes to the language itself, since it lacks many things that will allow it to be quick:

    a) generics, first and foremost. It's another thing to directly access an array's items and other thing to cast it to the proper type at every access.

    b) every object reference is a pointer. All objects are accessed via their pointer, which is not a simple pointer, but a reference-counted one.

    c) The JVM. JIT has many goodies for some type of applications, but...

    All these are for static applications, I have to say. For the web, it might not play a role.

    I have a proposition to Sun: migrate your Java libraries to C++, and have them be 100% source code-level compatible across all operating systems. The Java's libraries are top-notch, it's performance that hurts it. Let Java call native C++.

    1. Re:Java is slow. by Anonymous Coward · · Score: 0

      Try eclipse - www.eclipse.org. SWT is pretty fast.

    2. Re:Java is slow. by Anonymous Coward · · Score: 0

      All of you examples just shows how slow is Swing compared to native applications. Yes, we all know that Swing is slow and memory intensive. It's not a problem of Java itself, rather of implementation and limitation of Swing.

      I suggest you to try Eclipse. It's written in Java but uses SWT instead of Swing as its graphic toolkit. It's lot more responsive than Swing and look and feel just like any other native applications.

      Other than that, I think only serious performance problem is JVM startup time. I hope they could deal with it in their next release.

    3. Re:Java is slow. by cakoose · · Score: 1
      b) every object reference is a pointer. All objects are accessed via their pointer, which is not a simple pointer, but a reference-counted one.

      I'm pretty sure the Sun JVM (and most others) doesn't employ reference counting.

    4. Re:Java is slow. by Anonymous Coward · · Score: 0

      1) there is still no Java-based office application suite (and even if there is one, it is surely not widely known). You know why ? Because Java is slow.

      http://www.thinkfree.com

      3) I've got JBuilder 4.0 on my home Athlon 650 MHz/650 MB RAM and it is slow to the point of being unusable. Ok, that's an old product but...

      So get a new one or try Eclipse. I used 3.5 but switched to eclipse, gave my old 750 MHz laptop new life.

      http://www.eclipse.org

      TH

  104. but don't generics make (heavy) use of casts? by Ars-Fartsica · · Score: 1

    My understanding is that the Java generics model is simply syntactic sugar over a bunch of casts (??)

    1. Re:but don't generics make (heavy) use of casts? by CognitivelyDistorted · · Score: 1

      Not quite. Since the compiler has more type information it can safely omit most of the casts.

  105. 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

  106. more unsubstantiated gibberish by Anonymous Coward · · Score: 0
    sorry, but you're just rehashing the same old tired arguments sans benchmarks on real programs.

    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.

    In theory, but in reality, your premise is false. Run tests on REAL PROGRAMS.

  107. You're not being trolled, you're a moron. by Anonymous Coward · · Score: 0
    mutable String objects
    String objects are immutable.

    You seriously do not know what you are talking about. Take a class or something, because you're way out of your league. I doubt you can really program in C++, because I don't think you understand object-orientation. I think you were programming C++ as if it were C. It sounds like your problems are a result of poor programming for OO.

    The supposed examples you give are bullshit, and prove that you're fucking incompetent.
    A tax adapter that did operations for each order.
    There are tons of transaction-based systems in Java. I see no reason why you're application is that special. I've worked on ones that support millions of concurrent users, manipulating 50+kB files, at thousands of transactions per second.
    Text parsing/processing that operates on each line of many megabyte files.
    This is very common. Lots of programs do similar things. If it's not working, it's your fault.

    I just had to reply to this, because your obvious ignorance (and associated arrogance) are really irritating.
  108. your weird proselytic sig by alienmole · · Score: 1, Insightful
    At the time of writing, your sig reads:

    Jesus of Nazareth did not die so we could enjoy eggs and chocolate bunnies!

    Are you sure? Christians enjoy eggs and chocoloate bunnies because despite the attempts of many clueless religious nuts, Christianity did not succeed in stamping out the natural human instinct for enjoying life, in the form of festivals and celebrations in which everyone can share - not just those who believe that their life is controlled by an imaginary being.

    Celebrations of renewal and fertility in springtime, involving common symbols such as eggs and rabbits, were widespread before Christianity came along, and they continue today. In one sense, your sig is accurate, in that Jesus of Nazareth has nothing to do with it, other than the fact that the churches that exploit his name co-opted other traditions as part of their relentless assimilation of followers. But in another sense, the sig is wrong, since based on his record, I suspect Jesus of Nazareth would have no problem with people enjoying eggs and chocolate bunnies, even - and perhaps especially - on the anniversary of his death.

    1. Re:your weird proselytic sig by fiftyfly · · Score: 1
      <snip>...I suspect Jesus of Nazareth would have no problem with people enjoying eggs and chocolate bunnies, even - and perhaps especially - on the anniversary of his death.
      Not to mention that the church's attempts to co-opt and/or erradicate pagan holidays, customs & symbology would seem rather effective when the example of ancient fertility symbols rendered as impotent (so sorry ;p) as $0.25 candy at your local walmart is considered.
      --
      "Sanity is not statistical", George Orwell, "1984"
  109. Performance legend #1:Synchronisation is slow by Mike+McTernan · · Score: 1

    Urban performance legend #1: Synchronization is really slow

    I'm not sure about this. I read advice on the web saying the synchronisation was slow and so changed all instances of Vectors into ArrayLists in a program I was writing. The program is very simple and just reads binary data and translates into strings, yet making this change certainly made the program run a lot faster (about 5%).

    Urban performance legend #2: Declaring classes or methods final makes them faster

    Well, lets face it - it can't make them any slower, can it?

    Urban performance legend #3: Immutable objects are bad for performance

    When I use the in built JVM profiling for my program, I find that code in the String class is the largest bottleneck by far. The program does a number of string concatenation using '+', and changing this such improved things a fair amount, although doesn't stop the String class having the largest bottleneck. I'm using the Java 1.4.1 JDK tools - maybe commercial compilers & JVMs are better, who knows

    Essentially, higher level languages should result in faster code than lower level ones, since the compiler has more scope for optimisation and also gets more information about what the program is trying to do, although this Urban performance legends article seems a bit shaky to me.

    --
    -- Mike
    1. Re:Performance legend #1:Synchronisation is slow by fizbin · · Score: 1
      If String class methods are showing up as the largest bottleneck, it's not concatenation that's doing it - unwise/unncessary concatenation causes StringBuffer., StringBuffer.append, and StringBuffer.toString to rise to the top in profile output.

      Although I've never seen String class methods being a huge bottleneck, my initial guess is that somewhere you're ignoring the immutable nature of String and doing things similar to:
      String s = new String("CONSTANT");
      (and yes, I know that reflection lets you abuse Strings in unnatural ways - ignore that for now)

      My suggestion would be to download hpjmeter or some similar tool for displaying the jdk's hprof output, generate cpu sampled hprof output, and look to see where you're calling these String methods that are bubbling to the top in the profiled output. For reference, we use the following command line when profiling our application:
      $JAVACMD $JAVAARGS \
      -Xmx100m -Xrunhprof:cpu=samples,thread=y,depth=16,cutoff=0 -server \
      -classpath "${CLASSPATH}" com.ourcompany.OurMainClass "$@"
      And yes, that "synchronization isn't slow" bit is, in my experience, just wrong. Unless you've got some heavily CPU-bound process (or, possibly, are writing something involving user interaction) it's better to use as much non-blocking I/O as possible and stick to single threads whenever you can.
  110. You are being lied to by MarkLewis · · Score: 1

    Much has been said about how this article makes claims and backs them up with nothing. So I decided to run some benchmarks of my own. Tested on both uniprocessor and SMP, with a bunch of different code paths, using the very latest JVM.

    I tested the assertion that synchronization isn't all that slow. First, I started by writing a simple test that goes into a loop and does enough work to not be optimized away by the compiler, but no more. This test showed synchronization to be about 200 times slower on SMP and between 50-100 times slower on uniprocessor.

    But, as the author states in the article, that's a contrived benchmark, so I won't bore you with the details. He claims that synchronization only adds constant-time overhead to a function, so that in any 'real world' function that does 'real work' the performance difference will be small.

    Fine, I'm willing to consider that. So I rewrote the test so that each method invocation allocated a 1024-byte buffer, wrote data to the buffer one byte at a time, allocates a new String, parses the byte-buffer to Unicode, and calculates the hashCode of the resulting String. That's heavier than most of the methods I write day-to-day, so let's see how bad the synchronization overhead is?

    On a dual-processor PIII-1266Mhz with 1G RAM and the latest (1.4.1_02) JVM with default settings:

    10,000 iterations nonsynchronized:
    0.67 seconds

    10,000 iterations synchronized:
    1.47 seconds

    So even in functions that perform 'real work', synchronization REALLY IS expensive. More than the rest of the method, which is a fair amount.

    Where does this guy get off claiming that slow synchronization is an Urban Myth when anybody with a decent grasp of the language and willing to invest a few hours running tests can prove him wrong?

    Source code for the test can be found at:
    http://www.lewisworld.org/~mark/Test.java

  111. If Java were faster, that would leave. . . by Anonymous Coward · · Score: 0

    If Java were faster, that would still leave 100 reasons why it sucks.

    Static typing. Variables that are not instances of classes. Classes that you cannot derive from, but if you forget to make your classes final, it's a security risk. Write once, test everywhere. Klutzy widget set, but Sun will not let you deliver anything but SWING with your IDE if you want it to have a Java logo on the box. It's outright war between Sun's installer and you-know-who's operating system to get things working/not working.

    Clueless managers who have fallen for the hype.

    I could go on. Really.

    Note: I am not saying that .NET is any sort of an alternative.

  112. 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.

    1. Re:using synchronized and a note on immutable by cakoose · · Score: 1

      Implementing it the way you did is correct, but it needs to acquire the lock on every call. The (ultimately incorrect) version described in the article tries to avoid locking in the common case. As I just learned, there is a subtle problem with that.

  113. Tu quoque by etymxris · · Score: 1
    String objects are immutable. Yes, I had a typo in one of my posts.

    When facing a troll, you can do something called the "mirror test". If something makes sense when redirected at the person saying it, then it has no relevance to the conversion. Let's partake in this exercise:

    You seriously do not know what you are talking about. Take a class or something, because you're way out of your league. I doubt you can really program in C++, because I don't think you understand object-orientation. I think you were programming C++ as if it were C. It sounds like your problems are a result of poor programming for OO.

    The supposed examples you give are bullshit, and prove that you're fucking incompetent.

    See, that was easy. No content. And what you say afterward makes me know you're full of shit:

    There are tons of transaction-based systems in Java. I see no reason why you're application is that special. I've worked on ones that support millions of concurrent users, manipulating 50+kB files, at thousands of transactions per second.
    I'll bite. What type of fucking system can process millions of users concurrently? Tell me, please. If you mean a stateless web app, then you're simply lying, because there is no concurrency going on for any significant percentage of those million cookies you have stored in a table somewhere. If you have a million concurrent users, then the data stored for each user can't be more than a few ints. If your user data isn't in memory, then it's not concurrent. That is, the user operations are not operating concurrently, and thus cannot said to be "concurrent".

    This is very common. Lots of programs do similar things. If it's not working, it's your fault.
    You're right. It was my fault for using Java. Java does many things well, but when performance is an issue, Java should be the last choice.

    I just had to reply to this, because your obvious ignorance (and associated arrogance) are really irritating. [See, that's the mirror test again.]
  114. Depends on the sort of memory usage by Trepidity · · Score: 1

    Depending on how your program uses memory, it could be that other standard sorts of garbage collection -- mark and sweep, for example -- actually peform faster than reference counting. This would be true if, for example, you have a small number of objects being referred to by a constantly-changing large number of pointers; then the reference-counting overhead would be enormous, while the mark-and-sweep overhead would be fairly small.

    In situations where CPU time is more important than RAM usage reference-counting could also be suboptimal, as you may not want to delete objects as soon as their reference count drops to 0 (instead you might want to wait for a lull in CPU usage and let an idle-priority thread clean them up when convenient). This is especially true if you have lots and lots of small objects (the CPU overhead of deleting objects 100x/second might be large, and if they're 50 bytes each, the RAM overhead of keeping them around a bit longer before deletion might be small).

    1. Re:Depends on the sort of memory usage by pyrrho · · Score: 1

      don't you use reference counting to mark things for deletion.

      In reference counting you don't have to delete or free the memory when the count goes to 0. I agree with you, you "collect" those later. In some cases, you don't have to collect, you just give the memory to someone else.

      --

      -pyrrho

  115. Go to the source ! by Anonymous Coward · · Score: 0

    The Java Sources!

    With the new JSPA, now any body can reimplement compatible Java VM taking benefit of the JCK / RI.

    Apache guys fight agains some Sun fellow to obtain this JSPA.

    Now we will see if the GNU gurus realy want an open Java or still preffer to get locked on their C++ ... hope classpath will not get stuck again !

    Tiger (the new upcoming Java) will be under JSPA. But will RMS and others noticed this is an oportunities to make things moves in the right way ?

    Hope so ...

  116. Sorry your upset about being a dumbass. by Anonymous Coward · · Score: 0
    What type of fucking system can process millions of users concurrently?
    Servers for cellular phone systems. When I was last involved, they were spec'd at 3,000,000 simulataneous users (worst case scenario), with a typical load somewhere around 1/3 of that.

    You're right. It was my fault for using Java [when I don't know what I'm doing.]
    Yes, Java is not the best performing language in many cases (not counting cost/time of development and when predicitve/optimizing JVMs outperform C code). However, for the trivial shit you seem to be doing, it's more than sufficient.

    You don't see me getting all upset over the performance of Java, because I've never had a problem getting it to perform (I've written telecom load testing tools in Java). I have rarely done any JVM tuning either, only when changing memory limits in the system. Since lots of other people can use it fine, you might want to consider that the problem is you, and not the language. Hell, you could use a Java to assembly compilation chain, and I'll bet your code would still suck.

    Just accept the fact that you don't understand it. Not everyone can understand everything (some less than others). You've had problems implementing some relatively simple things in Java (the kind of stuff it's traditionally pretty good at). Stop trying to place the blame elsewhere.

    Where Java really falls short is in numerically intensive computation (ie. the Monte Carlo simulation someone mentioned earlier), and in GUIs (deep inheritance hierarchies are the main culprit here).

    You can call me a troll, if that really makes you feel better about yourself. However, that doesn't change any facts.
    1. Re:Sorry your upset about being a dumbass. by etymxris · · Score: 1
      Not getting upset? Jesus, man, then how do you explain your last post?

      You can call my work trivial when you show me your own regular expression parser written in Java (no help from the API allowed). It's not trivial, I don't care how smart you are. Incidentally, I've programmed my own languages before, so I have some decent understanding of how computer languages work. Nothing complicated language wise, but it doesn't take much for the task to be extremely complicated to implement. And no, I didn't use lex or yacc.

      I think you have a differing opinion of what is "just fine" than I do. You'd probably look at my program and see nothing wrong with it. But that I could optimize it and get 80% better performance by avoiding allocation altogether tells me that something is wrong with the garbage collection of Java.

      Just accept the fact that you don't understand it. Not everyone can understand everything (some less than others). You've had problems implementing some relatively simple things in Java (the kind of stuff it's traditionally pretty good at). Stop trying to place the blame elsewhere. [Mirror test]

      Servers for cellular phone systems. When I was last involved, they were spec'd at 3,000,000 simulataneous users (worst case scenario), with a typical load somewhere around 1/3 of that.
      Java server for such a task? I highly doubt it. Java client I could understand. In any case, using Java probably necessitated about 10 times the hardware that a lower level language would demand. I mean, you could make it as efficient, but only if you avoid java.util.* and any serious allocations.
    2. Re:Sorry your upset about being a dumbass. by Anonymous Coward · · Score: 0
      Java server for such a task? I highly doubt it.
      Of course you do.

      That's the problem here. It's possible that it could have been a bit more efficient in another language (but testing didn't reveal any major performance gains by replacing some of the subsystems with C code). When you realize the development costs that get slashed, and the massive improvement in time-to-market, as well as the higher degree of maintainability, you see why Java was a good choice. It really seems like you are clinging to this idea of Java not being having really bad performance, which in most situations, is not the case. As for servers, Java is quite good (like I said before it falls down on numerically intensive and GUI stuff).

      The only hardware issue we ever had any problems with was memory. Java is a memory pig, that's certainly true. But, since the production systems were loaded with everything Sun could squeeze into each box (as per customer demand), that wasn't much of a problem for us. As long as you're not leaking memory, or doing a really inefficient implementation, memory will rarely be a problem. A lot of the programmers I worked with came from doing C for the military, and they sucked at anything regarding Java and/or OO. I'll bet the memory use could've been much better with some more competent Java people.

      your own regular expression parser written in Java
      I haven't written a regex parser in Java, although I've used APIs written by others. They worked fine. I have designed languages, and used Java as the development language for the parser/compiler. Again, it worked quite well, and I doubt I would've had a noticeable gain by using C (especially since it would've been slower).

      And no, I didn't use lex or yacc.
      Well, you should. That's what they're there for, to make things easier. I'm sure they'd generate more efficient code than just about any experienced programmer could turn out (and in far less time). If you're using Java, you should be writing parsers with JavaCC (kind of an ebnf syntax).

      This could go on forever. The point is, for most applications Java performs quite well. Especially parsing a few MB of text, doing some basic financial stuff (ie. not derivatives analysis), there's no reason to have performance issues with Java (other than poor programming).
    3. Re:Sorry your upset about being a dumbass. by etymxris · · Score: 1
      I haven't written a regex parser in Java, although I've used APIs written by others. They worked fine. I have designed languages, and used Java as the development language for the parser/compiler. Again, it worked quite well, and I doubt I would've had a noticeable gain by using C (especially since it would've been slower).
      You're changing the topic. Yes, a regular expression parser can be written efficiently in Java, as I did. But you basically have to leave OO aside (minus the API). If the entire point of your application is to do regular expression parsing, then why use Java when it's more complicated than using C/C++. Besides, the tasks I needed to perform were especially stressful--they involved evaluation of a single regular expression that was about 200 lines or 5000 characters long against successive files. This will crash many regular expression parsers (MKS's AWK is an example).

      But this is all moot because you were accusing me of failing to program trivial tasks correctly. Writing a regular expression parser is by no means a trivial task. You do not realize the complexity of the task by simply using an API. First you have to construct a NFA using lamba transitions, then you have to make it a DFA by collapsing the lambda transitions and removing any duplicate transitions. Ok, not too bad. Now you have to come up with a way to track the "back refs", so you have some info about what was just parsed.

      If I used lex and yacc I would've learned how to use lex and yacc. I wouldn't have learned to parse a language. It's nice to have an API that helps with some tasks. But what about when you have a task for which no cookie-cutter is provided by the API. I know I'd be able to still come up with a solution, but you seem to rely too heavily on APIs.

      This could go on forever. The point is, for most applications Java performs quite well. Especially parsing a few MB of text, doing some basic financial stuff (ie. not derivatives analysis), there's no reason to have performance issues with Java (other than poor programming).
      Yes, this could go on forever. If you are programming a database intensive application, or a network intensive application, then, in most circumstances, you application will be so bottlenecked on the database or the network that Java will take 5% CPU time while C++ will take 2.5% CPU time. But these are not the tasks I'm talking about. I'm talking about categorizing and movement of significant amounts of data. For example, interfacing with Taxware required creation of char buffers of several thousand characters for each transaction. Maybe this comes close enough to the "numerical tasks" you keep referencing.

      One financial company I knew could only get appropriate performance by creating a Berkeley style DB and leaving it in RAM. Everything was coded in C/C++. And I know these people didn't have 3 million concurrent users. So I must wonder what the complexity of the task is that your application was so smoothly able to perform.

      Java does slash development time for some tasks. But for many, it takes more development to do something in Java. Then Java loses in performance and development time. So why use it for these tasks? I guess it shouldn't be.
  117. 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.
    .

    1. Re:White coats, step right this way... by Markus+Registrada · · Score: 1
      I haven't seen many C or C++ programs where I needed to pass a -Xmx option. When I click on a desktop icon for a Java program, does it have to pop up a dialog box to ask me to estimate the memory it should use? If not, how does it know what other programs I am running that also use or might use memory? It seems as if the Java program had better be the only program running on the machine. Many of us like to run more than one program at a time. We like to call that multi-tasking. (Maybe it's silly, these days, to use one computer for more than one thing, but sometimes we like to run more than one program to do even just one thing. It might be thought of as an alternative to threading, which tends to introduce otherwise unnecessary complexity.)

      The better JIT runtimes run bytecodes for most of the code, and compile only the more heavily-used functions to machine code. They collect statistics on which functions and loops are (re-)entered most often, and compile them. The clever ones don't optimize the first time, but only optimize the ones that still take the most time. As a result, the JIT compiler, the bytecode interpreter, and its instrumentation continue to compete for L2 and/or L3 cache long into the runtime of a program.

      JIT compilers are heavily constrained in the degree of optimization they can afford to apply because they are running when the program itself is supposed to be running. Also, since they are not operating on source code, much of the context is lost by the time they get a chance to operate. Bytecodes are not very expressive of programmer intent.

  118. For judz... by Anonymous Coward · · Score: 0

    Here's the code you need...

    for (i = 0; i cameraStore.size(); i++)
    {
    Camera c = (Camera)cameraStore.get(i);
    if (c.isAvailable())
    { //Print 'c' to textbox inside this 'if' block.
    }
    }

  119. 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!
  120. what I don't understand - Java vs C# by BigGerman · · Score: 1

    Java is interpreted (compiles to bytecodes)
    C# is interpreted (compiles to MSIL or whatever they call it today)
    Why my program (heavy on encryption) is 10-12 TIMES slower in Java version vs. C# version?
    Code is identical.
    Is it simply because Microsoft did a better job with the virtual machine?

  121. 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.

  122. Re:To what extent does this exist in other languag by The+Clockwork+Troll · · Score: 1
    Unfortunately, most profilers won't tell you that a certain code path only consumes a lot of time when variables a,b,x,y and z are set to 6.3, 5.7, 4.118, 2.05 and "albatross".

    (sigh)

    --

    There are no karma whores, only moderation johns
  123. 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.

  124. 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 Coward · · Score: 0

      What is the run-time overhead in using templates? At compile time, sure, but at run time there are only benefits. Clever use of templates can whittle your compiled code to about nothing. The use of STL algorithms is usually faster than hand-written loops.

      Good template optimization make the use of C++ for numerical simulation a possibility (see Blitz++), whereas this was never the case for plain C.

    2. Re:A few from C++ by Anonymous+Brave+Guy · · Score: 1
      What is the run-time overhead in using templates? At compile time, sure, but at run time there are only benefits.

      In theory, that's true at least to a degree, but in practice it tends not to be.

      Firstly, you have the bloating issue. On processors which have a relatively small first-level cache (i.e., most of today's major players) having two or three copies of the same algorithm specialised in different ways can be enough to cause cache misses when you're using them in the same area of the code. Having a single algorithm and implicit conversions of the parameters/return value to a common type might not.

      Granted you can write your template code as generic wrappers for basic algorithms, but often this is either irrelevant (if you could just let implicit conversions do the job anyway) or awkward (e.g., wrapping a void*-manipulating algorithm in a T*-manipulating template with type parameter T).

      Secondly, you have the fact that most library implementations aren't actually very good at providing specialisations where they should. By keeping the algorithm generic, you rely on a generic optimiser rather than the hand-coded, super-efficient assembler that is routine in a typical C library implementation. This one is clearly a quality of implementation issue, but in practice, the bar is pretty low, at least for now.

      The use of STL algorithms is usually faster than hand-written loops.

      That one's just way off base, I'm afraid. In fact, since most STL implementations are just header files containing templated code because no-one really uses export yet, much of the time the STL algorithms compile down to exactly the same code as an equivalent loop. You sometimes get a modest performance improvement because parameters passed to an STL algorithm are only evaluated once, whereas someone careless who sticks a call to container.length() in his for-loop condition will get it called as a side-effect many times. That's a pretty basic performance issue, though, and something even Joe Average Programmer would knock out if performance was becoming an issue.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    3. Re:A few from C++ by whereiswaldo · · Score: 1

      Exceptions cripple performance.

      Actually, exceptions can impact performance, if you are throwing the exception the majority of the time. If it is more the exception than the rule that the exception is thrown, your performance will not be affected.

    4. 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.
  125. The flaw with the "hand-optimised C" argument by Anonymous+Brave+Guy · · Score: 1
    I'm just saying that, over time, you may regret not knowing something well that is, in fact, more efficient and effective for writing compace and fast code.

    The problem with this is that it's almost impossible for regular developers to "hand-optimise" their code effectively on any platform today.

    Sure, you can write in raw assembler, or you can write in C and be careful of low-level details. But the instruction sets and performance characteristics of modern processors are so counterintuitive at times that usually you're just second-guessing the chip designers, and often you'll be wrong as a result.

    There are people who are paid to understand how all the nitty-gritty pipelining, cacheing, and other tricks work in modern processors. They are compiler writers and library implementers. Few other people have the time and resources to invest in acquiring the same level of expertise. Most of us would be better off using a language that is of a generally suitable nature and letting the compiler/interpreter/JIT compiler/optimiser do its thing.

    By the way, did you realise that some really quite high level languages now compile down to give more efficient code than C a lot of the time? Why? Because they provide high level features with good underlying implementations that are carefully designed around the target architecture. With a clean programming model, they can often optimise a lot of apparent work away as well. Using a low-level language like C denies the writer of the compiler/optimiser the same degree of assumption, so they can't help you as much as a HLL compiler/optimiser can.

    For example, Intel's x86 series chips have REP and CMPSx instructions that seem to be carefully designed to work with strings. Do you know what you see if you look at typical strcmp code in any recent C standard library implementation, though? It looks like a whole mess of random assembler, several lines long, because it's been tuned to the specific target architecture's characteristics. It doesn't look like REP CMPSB.

    The whole argument about using low-level languages for efficiency starts to break down around this point. In fact, it's all backwards. The higher the level of language you use, and the cleaner its programming models, the more the compiler/optimiser can help you to get efficient output code. In today's world, you use low-level languages for control and flexibility, but unless you really are an expert on your target architecture, you don't use them for efficiency.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  126. Re:To what extent does this exist in other languag by WolfWithoutAClause · · Score: 1
    Unfortunately, most profilers won't tell you that a certain code path only consumes a lot of time when variables a,b,x,y and z are set to 6.3, 5.7, 4.118, 2.05 and "albatross".

    Yeah they do. If it's a lot of time. If it's just more than it should have been in that scenario, then no, practically no profiler gives you any idea; it just gives you the average time spent in that routine, not the worst case AFAIK.

    --

    -WolfWithoutAClause

    "Gravity is only a theory, not a fact!"
  127. Re:To what extent does this exist in other languag by pla · · Score: 1
    I wonder to what extent this exists in other languages?

    The author of the linked article gives a nice neat (though perhaps not intentional) summary of why Java opts take on an almost "urban legend"-like status:

    First of all, microbenchmarks rarely measure what you think they're measuring. In the presence of dynamic compilation, you have no idea what bytecode the JVM decides to convert into native code or when, so you can't really compare apples to apples.

    In C, or just about any truly compiled language, you most certainly can measure the performance of two different ways of doing something.

    Then again, this counts as one of the many factors in the C-vs-Java wars... C programmers like determinism. Java programmers like idiot-proofness. If you need to factor in the amount of time it takes to unload the gun in "point at foot, pull trigger", you'll never really get a good idea of how long it takes to "shoot self in foot". ;-)
  128. Swing is evil. by pegacat · · Score: 1

    I wrote a fractal planet surface generator in java. It spat out a gif image 2000 pixels by 1000 pixels, doing about 8 floating point operations on each pixel... so ~ 16,000,000 operations, not counting the gif encoding.

    The whole thing ran, from scratch, on my ancient 450Mhz PIII in *under* a second.

    But loading the resulting gif into a paint program to look at it was a pain... so I added a swing display class...

    Suddenly it took ~ 5 seconds to run!

    So I trimmed code, until I was back to a 'hello world' program in swing. ~ 3 seconds.

    This is generally my experience; java is reasonably quick for data processing (not ultra-quick, but not too bad), but Swing and the GUI stuff let it down big time. I've heard IBM's swt stuff is good, but haven't tried it.

    Oh yeah, and most of the article seems like bullshit. I've seen bulk benchmarks showing the opposite of what this guy says, and I'm too old to believe proofs by assertion any more.

    --
    Wer mit Ungeheuern kämpft, mag zusehn, dass er nicht dabei zum Ungeheuer wird.
  129. Already exists by Jonner · · Score: 1

    Echidna already does this. Also, see my other comment.

  130. mark and sweep vs. reference counting by Trepidity · · Score: 1

    Mark and sweep doesn't use reference counting. The mark stage looks at all pointers (references in Java), follows those pointers (and anything pointed to by the targets of those pointers) and marks all the things it finds as "reachable." Then the sweep stage goes through memory and deletes everything that wasn't marked as reachable.

    In the case I mentioned (not many objects but constantly-changing pointers to them) this could have lower overhead, because you only do the mark stage periodically, instead of having to update a reference-count variable every time a pointer to the object changes (which could be potentially millions of times more often than the mark-and-sweep GC runs).

    1. Re:mark and sweep vs. reference counting by pyrrho · · Score: 1

      thanks for the explanation.

      I hadn't thought about that because of the enormity of following every pointer! But as you say, this can be done more cheaply, concievably, if it doesn't happen very often.

      --

      -pyrrho

  131. the biggest urban legend... by Anonymous Coward · · Score: 0

    ...is that Java is an excellent and fast language.

  132. try jEdit by Anonymous Coward · · Score: 0

    jEdit is the best text editor I've ever come across. I wasn't looking for a java app, merely a free text editor that would allow me to easily define my own syntax highlighting (for an obscure scripting language for a data acquisition tool that still makes me shudder when I think about it). that was nearly 3 years ago and I've been using it every day ever since. it's editing features are superb, it's endlessly configurable and is extensible through its plugin mechanism to the point of being a fully-featured java IDE. the performance is good enough that I the fact that it's java is a non-issue. it just isn't something that I have to think about. I'm not claiming that it's as fast as it would be if it had been written in C++, nor am I claiming that java / swing is the perfect solution for all desktop apps (it's certainly not) but it IS a very useful java desktop application that I use 8 hours a day every working day of my life.

  133. Paraphrasing your question.... by jrumney · · Score: 1

    If each tape measure weighs 11 ounces, how long is a piece of string?

  134. Conclusion: memoize function results by fizbin · · Score: 1
    The template meta-program is an unfair comparison for another reason: it's using a completely different algorithm from the other code. Hell, I could beat the icc-compiled C code using perl if I used that algorithm.

    To be fair, the template method needs to be compared to this java code:
    Map fmap = new HashMap(100);

    long fib(int i) {
    if(i<=2) return 1;

    Integer key = new Integer(i);
    Long res = fmap.get(key);
    if (res == null)
    {
    fmap.put(key, res = new Long(fib(i-1)+fib(i-2));
    }
    return res.longValue();
    }
    And similar C code to be compiled with icc or gcc.

    For extra speed on the java side, you might even try storing the result in one of those fancy new LongBuffer objects, or, since here we have a limit on what we're calculating, a simple long array.

    But at this point it's silly - template metaprogramming wins here because it is (behind the scenes) using a better algorithm.

    Which, I suppose would not be an overly bad lesson to take away from this: templates can do things faster because they transform into better algorithms behind the scenes. However, even though I believe that statement to be true generally, I still think that this example is cheating, as the memoizing that templates do for you is often not going to be what you want.

    For reference, the perl that uses this is:
    my %fmap=();
    sub fib
    {
    my $i = shift;
    if ($i <= 2) {return 1;}
    return ($fmap{$i} or
    $fmap{$i} = fib($i-1) + fib($i-2));
    }

    print fib(45),"\n";
    1. Re:Conclusion: memoize function results by iGN97 · · Score: 1

      I wouldn't really say that the algorithm is different, it is just implemented in an environment that defines a hard constraint; it's always deterministic what output values are produced from a set of input values (no side-effects). This means a template can (and will) be expanded only once, and there is implicit caching.

      This could be automatically done by both Java and C if they either could detect that there was no side effects, or they provided explicit syntax for it.

      Could this indeed be why the Java runtime is faster than the gcc-code, automatic caching of output for a given set of input after some analysis on whether the function has side-effects?

  135. .NET slower than Java? by cpfeifer · · Score: 1

    According to this article on theserverside.com, in one person's benchmarks, .NET is slower than Java. YMMV and all that.

    --
    it's not going to stop until you wise up, no it's not going to stop. so just give up.
  136. The best Java Garbage Collection by Anonymous Coward · · Score: 0

    Collect all the Java programs you can get your hands on.

    Throw them in the garbage.

    Problem solved.

    I am serious!

  137. UnsynchronizedStringBuffer by fizbin · · Score: 1
    That's a nice idea; in the Simpsonized words of Steven Hawking, "I may have to steal it".

    In trade, one thing you might consider allowing is several constructors of the form:
    UnsynchronizedStringBuffer(Object stuff)
    UnsynchronizedStringBuffer(Object stuff1, Object stuff2)
    UnsynchronizedStringBuffer(Object stuff1, Object stuff2, Object stuff3)
    ...
    Then, you could replace common idioms like this:
    log.debug("Found object " + objname + " with value:" + foundThing.value());
    with:
    log.debug(new UnsychronizedStringBuffer("Found object ", objname, " with value:", foundThing.value()));
    (And yes, you should also be using log.isDebugEnabled() if your logging facility has that)

    The advantage of this idiom over
    log.debug((new UnsychronizedStringBuffer(80)).append("Found object ").append(objname).append(" with value:").append(foundThing.value()));
    is that you don't have to get that "80" constant right in order to avoid potentially expensive re-allocating.

    Of course, at this point it might well be worth it simply to have a class with a static function called "BetterStringConcatenation" or similar which is overloaded similarly (i.e. to take a huge number of different objects) and simply returns the string made by concatentating the right ones together.

    The step after that is to hack a java compiler (e.g., jikes) so that it uses your BetterStringConcatenation internally whenever + is used for string concatenation... hrm...
  138. What people "obviously" should know... by Anonymous+Brave+Guy · · Score: 1
    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.

    So much for the language that removes all those nasty things that stoopid programmers get wrong. You still have the issue of equality of value vs. equality of identity, you just have nastier syntax for it.

    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.

    Sure. Just as it's obvious that you don't start coding serious C++ without knowing the RAII idiom, you don't start coding serious Perl without understanding the caveats of eq vs. ==, and you don't start coding C without knowing that gets is fundamentally flawed. Except that actually, many people do.

    I'm afraid your post actually stands against one of the biggest myths of them all: that Java is much safer than other comparable languages, notably C and C++, because of the limited feature set it provides. The reality is that you can still screw up in Java, and it really isn't much harder than in any other language of a similar level. There are good reasons to use Java for many projects, but immunity from developers who haven't done their homework ain't one of them.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  139. Re:To what extent does this exist in other languag by whereiswaldo · · Score: 1

    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.

    Good point. At the end when everything is working fine, you manager might say something like "everything is working just fine. Why do you want to spend the next two weeks on performance issues? I have more higher priority things for you to do".

  140. Re:To what extent does this exist in other languag by whereiswaldo · · Score: 1

    The old myth that floating point operations are slower than integer is wrong too. We tested that one 5 years ago and a floating point operation of the same values often beat the integer operation.

    Very interesting. I would think that since floating point storage is greater than integer storage (at least on 32-bit PCs), the speed would automatically be better for integers. Can you give more information?

  141. Toward the uninformed by fizbin · · Score: 1

    Why you might make some good theoretical points, some of your assumptions are off. I heartily recommend to you reading Sun's java manpage and searching for the word "default" before making statements about what the default behavior of java is.

    By default java will limit the heap size to 64 MB If, as with most modern machines, you have significantly more than 64 MB to devote to user-mode applications, then the default settings will not in fact, as you contend, make performance horrible the instant more than one java application is launched. Also, keep in mind that with java, the JIT can if it wishes to do so move frequently accessed objects so that they are on adjacent pages of memory. This can dramatically reduce paging latency as compared to other code.

    As for your points about L2 and L3 instruction caches - I suppose. At the very least, I don't know of any reason why it is obviously false. I'd need experimental confirmation first before I'd be willing to accept this.

    1. Re:Toward the uninformed by Anonymous Coward · · Score: 0

      You post no proof of your own assertions whatsoever - you only make up other unproven facts. Here's a tip - if you want to refute an argument - provide either hard evidence or an example that backs up your claim. If not, you're just one of a million other Slashdot blowhards.

  142. Swing's single threaded-ness by Steveftoth · · Score: 1

    I think that the real reason that swing is single threaded is because it's easier to program with if you only have one thread dispatching events and doing drawing.

    That way the application programmer doesn't have to bother with syncing on the data properly.

    Say that you had one swing thread that dispatched events, and another that only drew the screen.

    Fine and dandy right? Well this is a PITA for all application programmers. While this will probably give you maximum responsiveness to the GUI, it's also the larger source of problems for a programmer who doesn't know anything about multi-threaded programming (like most people).

    First off you must sync on every change an event causes to the data that is accessed for drawing. Any data that the drawing code requires must be locked before modification. The other choice is to copy ALL display data and then fire it off to the display thread, not the best idea in the case of say, JTables.

    Secondly, the likleyhood for deadlock is high. Of course there would be defined protocols for locking on shared objects between the display and event threads, but programmers would either be ignorant of them or ignore them. (but it runs faster! even if it doesn't work half the time)

    Swing is IMO designed well but it suffers from bloat. Bloat of having the AWT beneth it and bloat from having to run on ANY platform. This causes it's responsiveness to go down overall.

    As far as running multiple independent applications at the same time in on JVM, it's possiable but you have to re-write the AWT shared classes (like Toolkit) so that they expect it. With the ability to have multiple event threads for seperate applications and also you would probably have to create a generic library for sharing data among the different applications. I wish it were as easy as creating different class loaders for each seperate application, but the Native code assumes only one event loop per application, and dlls can not be dynamically loaded in the same way as classes. ( they cannot be linked to multiple times, while you can load multiple versions of the same class with the class loader)

    BTW, the Swing event loop and the AWT event loop are the same.

  143. Re: Synchronization by Bob9113 · · Score: 1

    1: Synchronization.

    This is slow. Really slow.


    I think your test was flawed. Please see here for a test showing one popular usage of synchronization (lazy initializers). One million cycles takes about 30 milliseconds longer (a hair more than twice as long) for the synchronized version as for the fastsynched (effectively unsynchronized after the first call) version. Unsynchronized actually came out slower, showing that compiler behaviour is probably a bigger issue.

    30 milliseconds per one million cycles. The extra 6 lines of code (and their extra defect opportunities) cannot be justified in any but the most extreme performance optimization situation.

  144. Re:Java vs. RAM (OT) by fredrik70 · · Score: 1

    ROTFL... Here's my mod points when I need them....

    --
    if (!signature) { throw std::runtime_error("No sig!"); }
  145. Re:To what extent does this exist in other languag by fredrik70 · · Score: 1

    hear, hear, so true, used profilers for the first time at my old job. Was a dream to use, managed to increase the performance of my app (comm app tx/recv SMS messages) from 5 msgs/sec to ~50 msgs.sec. not bad. Should have been able to squeze out more, but that would have been pretty much a complete rewrite plus our database wouldn't have been able to cope with much more anyway(ppl apparently got it up to ~400 msgs/sec, but that's the Big Boys, read: Mobile Network Providers).

    --
    if (!signature) { throw std::runtime_error("No sig!"); }