Slashdot Mirror


Java Faster Than C++?

jg21 writes "The Java platform has a stigma of being a poor performer, but these new performance benchmark tests suggest otherwise. CS major Keith Lea took time out from his studies at student at Rensselaer Polytechnic Institute in upstate New York's Tech Valley to take the benchmark code for C++ and Java from Doug Bagley's now outdated (Fall 2001) "Great Computer Language Shootout" and run the tests himself. His conclusions include 'no one should ever run the client JVM when given the choice,' and 'Java is significantly faster than optimized C++ in many cases.' Very enterprising performance benchmarking work. Lea is planning next on updating the benchmarks with VC++ compiler on Windows, with JDK 1.5 beta, and might also test with Intel C++ Compiler. This is all great - the more people who know about present-day Java performance, the better.""

225 of 1,270 comments (clear)

  1. Um, it's online by JoshuaDFranklin · · Score: 5, Informative
    If you want, you can read the actual author's piece instead of a news story about it:

    The Java is Faster than C++ and C++ Sucks Unbiased Benchmark

    1. Re:Um, it's online by jdhutchins · · Score: 4, Insightful

      Just becuase you can't write a kernel in it doesn't mean the language is worthless. There are many things that you can do very easily in Java that would be more difficult in other languages, and Java makes it impossible to write many security bugs that plague other languages. You can't do EVERYTHING in Java, but you can do quite a bit.

    2. Re:Um, it's online by Too+Much+Noise · · Score: 3, Informative

      erm ... I only checked the fibonacci routine, but it's actually quite funny - he's branching recursive calls, a clear case when a smart-enough runtime optimization would work better. I mean, any reasonably smart optimizer would eventually figure out that there are too many calls to the same function with the same argument to just stand by and watch. I'd say that given this difference c++ did quite alright in that one.

      So yes, there are cases when runtime optimizations that are unavailable at compile time can speed things a lot. Does this make Java faster? yes, if you look at the right corner case. Hell NO, if you look at the wrong one.

      The right tool for the job, as usual. And the right tool wielder, otherwise any tool will suck.

    3. Re:Um, it's online by mukund · · Score: 3, Informative

      Your wish just came true. Check out the JNode project.

      --
      Banu
    4. Re:Um, it's online by poot_rootbeer · · Score: 3, Insightful

      until one can write an OS kernel in it, Java is still not what I would personally look to for the future of software development.

      That's a silly thing to say.

      How many OS kernels are going to be written in the next ten years? And how many business applications? And the ratio of the latter to the former is what, 10,000 to 1?

    5. Re:Um, it's online by cheesybagel · · Score: 4, Informative
      I just looked at hash (C++, Java), but it seems he uses C++ STL and the Java API. This may end up being more of an API than a language test...

      It also does stupid things. Like this:

      int c = 0;
      for (int i=n; i>0; i--) {
      sprintf(buf, "%d", i);
      if (X[strdup(buf)]) c++;
      }
      When this would have worked just fine:
      int c = 0;
      for (int i=n; i>0; i--) {
      if (X[atoi(i)]) c++;
      }

      The alternative is actually shorter, besides being faster and using less RAM.

      I think the person which wrote this didn't know how to program in C++ very well. The two pieces of code are not even equivalent. The second loop is traversed backwards in the C++ version while it is not in the Java version. Don't ask me why.

    6. Re:Um, it's online by Anonymous Coward · · Score: 5, Informative

      It also does stupid things. Like this:

      int c = 0;
      for (int i=n; i>0; i--) {
      sprintf(buf, "%d", i);
      if (X[strdup(buf)]) c++;
      }

      When this would have worked just fine:

      int c = 0;
      for (int i=n; i>0; i--) {
      if (X[atoi(i)]) c++;
      }


      The code is dumb, yes, but you are wrong, nonetheless. That code won't even compile. I think you meant itoa(), which would be about the same as sprintf in terms of functionality.

      That for() loop is not equivalent to the Java code's for loop, either. In the java code, he used

      if (ht.containsKey(Integer.toString(i, 10))) c++;

      which means that he should have used

      if (X.count(somestringrepofi)) c++;

      X[somestringrepofi] will create an entry for the key if it is not found, making it very different from containsKey().

    7. Re:Um, it's online by Tranzig · · Score: 2, Informative

      The second loop is traversed backwards in the C++ version while it is not in the Java version. Don't ask me why.

      There is an instruction called loop in the x86 instruction set which decreases the value of the register cx by 1 on every iteration, until it becomes 0. So by writing decrementing for loops, it could be transformed to a mov and a loop. Two decades ago it was faster than increasing a variable, checking if it reached the required value and if it's less then jumping to the begining.
      But nowadays x86 processors work different, and loop became slower than the jumping method. It seems the writer of this code forgot this one. Anyways, the optimizing compilers don't generate loop instructions for decrementing for loops anymore.

    8. Re:Um, it's online by kin_korn_karn · · Score: 2, Funny

      Yes sir, Professor Knuth.

    9. Re:Um, it's online by dnoyeb · · Score: 2, Funny

      It does not matter. As I have said each time this stupid question comes up the whole thing is moot.

      Java VMs are written in C++ among other languages. This issue is just plain silly.

    10. Re:Um, it's online by Anonymous Coward · · Score: 3, Insightful

      Thank you! I am not the only one that noticed that these are not even equivilant code. Using sprintf when you expect speed is stupid. sprintf is for simplicity. Making 5 function calls in the middle of a for loop when once would have been fine is also stupid. Also Gxx type compilers are KNOWN to be slower. They are getting better. But the 3.3 branch is more of a staging for better things to come. I would be interested in the same thing done with the intel compiler. WITH all the sub libraries compiled with the intel compiler.

      Sure the code does the same thing. But the few code bits I looked at are not identical. To be a 'fair' test. All the functions need to be written in the same file. Then with *VERY* minimal changes work in both java and C. It wasn't even C++ code. Also if he used the G++ compiler? That is *KNOWN* to be very slow. They rewrote the sucker for 3.4. All the functions need to be called in the same way. All the loops need to be walked the same way. Etc...

      This test is bogus. I was willing to give the dude a listen. He even tries to defend what he does wrong. Its almost pathetic. For example he talks about GCC vs Visual studio. Then goes on to use G++. Interesting... Another good thing he does to 'obscure' the issues is to use overloads in C++ yet use method calls in Java. overloads are much slower. Usually firing off all sorts of copy constructors. Method calls are much faster. He even admits it C++ is faster in one case. Well that ONE case is about the only one where he has apples to apples. The rest are not. Also his 'method call' test is not the same thing. He did it in such a way that fires at least 2 copy constructors in the C++ way yet returns direct objects in the java way. C++ is slower in those cases. Well DUH.

      The idea that java or .net could catch up to C performance is interesting though. The code in these enviroents could be self tuning themselves. Did he prove that? I do not think so. NOT with that code.

      It is like I have always said. C/C++ does not produce awsome code. It lets you produce awsome code. But if your not carefull it lets you produce extreemly BAD code. It does not hold your hand. It has never claimed to. I could with a little bit of work (not as hard as some people would assume) produce the EXACT oposite results of what he got.

    11. Re:Um, it's online by ThosLives · · Score: 4, Insightful
      I agree about the non-equivalent code:

      A fun one:
      Java:

      public static int Ack(int m, int n)
      {
      return (m == 0) ? (n + 1) : ((n == 0) ? Ack(m-1, 1) : Ack(m-1, Ack(m, n - 1)));
      }

      C++:

      int Ack(int M, int N) {
      return(M ? (Ack(M-1,N ? Ack(M,(N-1)) : 1)) : N+1);
      }

      The C++ version could have been written IDENTICALLY (except for the 'public' modifier on the definition) to the Java version, but it was not. I'm not sure what the compiled difference might be, but there is a difference between these two bits of code, notably that in the C++ version there is a tertiary operator evaluated as an argument to a call to Ack, where this is not the case in the Java version. I would guess that this would be a more difficult thing for a compiler to figure out.

      The differences in the methcall sources are even worse; in the C++ version of NthToggle, there are unnecessary dereferences of the this pointer that will kill performance, as well as in the call to new NthToggle(val, 3) in the C++ version is written with the coded constant new NthToggle(true,3) in the java version! It's hardly fair to compare things of this nature.

      The trouble with benchmarking different languages is hard enough due to inherent differences between languages; it's not really enlightening to introduce artificial differences such as these.

      --
      "There are a dozen opinions on a matter until you know the truth. Then there is only one." - CS Lewis (paraprhase)
    12. Re:Um, it's online by javax · · Score: 2, Funny

      bah, its obvious that Java is Turing complete, so you can do everything with it.

    13. Re:Um, it's online by Pointer80 · · Score: 3, Informative

      Read the article. He said that he included JVM startup time in the benchmarks.

      /pointer

      --
      [%- PROCESS life -%]
    14. Re:Um, it's online by GooberToo · · Score: 5, Informative

      The more I read the code, it sure is starting to look more and more like an apples and oranges comparison; which is usually what happens when people do java benchmarks.

      As typically observed, I'm seeing the benchmarks take serious advantage of java's GC mechanism, whereby, they never pay the piper. With C++, the piper is constantly being paid. All of the benchmarks which allocate objects and then delete them, are therefore, invalid. To be fair, I think, you either need to add a System.gc() line in the java code where C++ is doing its deletes or you need to implement your own new and delete operators to function more in line with what java is doing. Until you do either one of those things, the comparisons where objects are being allocated and deallocated are invalid. And frankly, I'm still not sure adding System.gc() is even fair, on either side. The reason is, calling System.gc() simply hints that it's a good idea to collect. There is nothing which requires the collection to take place. So, technically, the call could still be many times faster. On the other hand, I don't know enough about how they handle their gc-hint logic nor am I aware of exactly how much overhead is involved in the actual collection process. If it occurs too often, the shift in workload may be too unfair. Nonetheless, it's a point of very serious contention.

      Just for kicks, I modified objinst.java with, "if( i%(n/1000) == 0 ) System.gc() ;", on the lines that the C++ code had it's delete. When I timed it, it was over twice as slow as the C++ code (24+s vs 55+s). Worse, when I ran it with a 1:1 ratio of delete:System.gc(), I simply got tired of waiting, having waited over 5 minutes.

      So, basically, I'm not nearly as impressed as I first was. Simplistically, it's starting to look like a serious apples and oranges comparison. Elsewhere, you can find other examples of just plain bad code. Where again, with correct C++ code, came in about twice as fast at the Java code, whereby, more optimizations were still possible with the C++ code.

      So, it looks like we're seeing a combination of things here. Looks like a combination of bad code, ideal corner cases for java's hot spot, and invalid comparisons with memory allocation.

      Sadly, I'm once again seriously disappointed in java.

    15. Re:Um, it's online by Alan+Shutko · · Score: 4, Informative

      As typically observed, I'm seeing the benchmarks take serious advantage of java's GC mechanism, whereby, they never pay the piper. With C++, the piper is constantly being paid.

      That's not a bug in the tests, it's a feature.

      The theory behind garbage collection isn't just that it allows the programmer to avoid the effort of watching when to delete things. It's that garbage collection can actually improve performance on certain workloads.

      Forcing a garbage collection for every delete is completely unfair, since it does a full scan of memory, as opposed to just twiddling bits to free a single data value.

      There's no memory leak for these benchmarks... both C++ and Java free all memory used when the process exits. Perhaps you'd prefer a longer-running test with lot of garbage generation (forcing gc to run at some point).

    16. Re:Um, it's online by Trepalium · · Score: 2, Interesting
      Not only that, but the 'fast path' in these otherwise identical functions is completely different. It means the C code may or may not be following more JMPs to get to the more common case. I have not read the code, but I would imagine the Java runtime could detect the more common path and optimize for it, but the C code is fixed in one direction. Maybe it optimizes it for C++, maybe it penalizes C++. Without taking a good look at the source, I can not say.

      Now, the other question is why use the ? operator at all? It's no faster than an if statement in a case like this. This code fragment would be much easier to read, for example:

      if (m == 0)
      return (n + 1);
      else if (n == 0)
      return Ack(m - 1, 1);
      else
      return Ack(m-1, Ack(m, n-1));

      (Please imagine it's indented properly because slashdot's ecode likes to strip spaces)

      The other benefit to this code is it should be clear to even the worst optimizer what it can optimize and what it can't.

      --
      I used up all my sick days, so I'm calling in dead.
    17. Re:Um, it's online by GooberToo · · Score: 2, Insightful

      That's not a bug in the tests, it's a feature.

      That's simply not true if you expect benchmarks to reflect real world applications. Sure, it might be true for trivial utilities but for applications that stay alive for long periods of time chugging along, which is probably the majority of the worlds useful applications, it makes the results invalid. Or, at a minimum, sets greatly unrealistic expectations.

      The theory behind garbage collection isn't just that it allows the programmer to avoid the effort of watching when to delete things. It's that garbage collection can actually improve performance on certain workloads.

      This is true..."on some workloads". I certainly recognize that fact. I hoped I had more or less pointed that out in my original message. At any rate, for real world workloads, I would offer that such expectations are not realistic.

      Forcing a garbage collection for every delete is completely unfair, since it does a full scan of memory, as opposed to just twiddling bits to free a single data value.

      Well, technically, even with the 1:1 implementation, it's not forcing collection. It's actually hinting to the GC system, that it should consider doing so. The GC is 100% free to ignore such a request. This is per the java specifications. Which, makes plenty of sense because doing so tends to greatly increase the window where GC can improve performance in various workloads. The problem is, I honestly don't know where implementation and specification lay. I've read many times that it actually does ONLY result in a hint to collect. Unless you can prove otherwise, I'm apt to lean in that direction. Which, actually means that the 1:1 implementation is a more realisitic apples to apples comparison. Can I prove that? No. I'm still hoping a java guru will come in with some insightful tidbits. ;)

      There's no memory leak for these benchmarks... both C++ and Java free all memory used when the process exits. Perhaps you'd prefer a longer-running test with lot of garbage generation (forcing gc to run at some point).

      Yes, I'm aware that there are no leaks. That's not my complaint. My complaint is that just about every java benchmark I've ever seen is so artificially small that they all appear to purposely avoid GC ever becoming part of the benchmark. Since most major applications simple don't start, run for 20 seconds and exit, I don't consider the presumed bevaior to be valid.

      The secondary point I was attempting to raise (along with awareness to the hidden gc issue) is that once Java is forced to start collecting, it's pays a significant cost. A cost, I'd hazzard a guess, that brings about the common complaints of Java. And that, I offer, is the difference between labratory tests and real world application. ;)

    18. Re:Um, it's online by Trepalium · · Score: 3, Insightful
      That's not a bug in the tests, it's a feature.

      It's neither a bug, nor is a feature. It's a difference, and possibly a testing methodology flaw.

      The theory behind garbage collection isn't just that it allows the programmer to avoid the effort of watching when to delete things. It's that garbage collection can actually improve performance on certain workloads.

      And on certain workloads it can decrease performance. Coders that know their languages should recognise the difference between the two memory allocation methods, and adjust their code accordingly. I seriously doubt you'd claim that java's garbage collector is always faster than manual memory management.

      Forcing a garbage collection for every delete is completely unfair, since it does a full scan of memory, as opposed to just twiddling bits to free a single data value.

      Perhaps, but it's also unfair to have a 'benchmark' that always pays the penalty of C++ memory allocation and deallocation, but never pays the penalty of Java memory allocation and deallocation.

      There's no memory leak for these benchmarks... both C++ and Java free all memory used when the process exits. Perhaps you'd prefer a longer-running test with lot of garbage generation (forcing gc to run at some point).

      Just because the memory is freed back to the system after termination doesn't mean it isn't a memory leak. It's a bad practice to allocation memory and not free it when you're writing C or C++ code. A longer running process would probably be more fair, or even a garbage collect at the end of execution. After all, on 'real' programs, a garbage collection is quite likely.

      --
      I used up all my sick days, so I'm calling in dead.
    19. Re:Um, it's online by ipfwadm · · Score: 4, Interesting

      I've read many times that it actually does ONLY result in a hint to collect. Unless you can prove otherwise, I'm apt to lean in that direction. Which, actually means that the 1:1 implementation is a more realisitic apples to apples comparison. Can I prove that? No. I'm still hoping a java guru will come in with some insightful tidbits. ;)

      Write a java app that does nothing but repeatedly call System.gc(). Run it with the -verbose:gc option, and watch the garbage collector go. Mind you, this is not 100% proof, but the fact that it prints out [Full GC] over and over again makes me lean pretty strongly in the direction of "the garbage collector actually runs in response to a System.gc(), it's not just a hint".

      One thing I would like Java to do is to allow me to delete objects manually. There are times when the garbage collector really sucks, but 95% of the time it's sufficient, in my experience. And yes, this experience comes from real-world apps.

      Regarding the original topic, I would bet that there are cases where Java really could give C++ a run for its money. However, one liability that Java has compared to C at least is that making everything an object adds a whole lot of object overhead. I had to write a file search routine as part of a Java app, and originally wrote it strictly in Java. The sheer number of File objects that get created by such a routine is ridiculous, and there's really no way to reduce the overhead by reusing the objects -- File objects are immutable. Calling out to JNI resulted in a 3 to 5x performance boost. Does this one example prove anything? No, but it's a heck of a lot more real-world than simply appending a string to itself a few dozen times...

    20. Re:Um, it's online by jovlinger · · Score: 4, Insightful

      "Any sufficiently complicated C or Fortran program contains an ad hoc informally-specified bug-ridden slow implementation of half of Common Lisp." -- Philip Greenspun

      / took way too long to google

    21. Re:Um, it's online by Sinterklaas · · Score: 2, Informative

      Technically, the majority of the time, according to java's docs, it should do nothing at all.

      It doesn't say that at all:

      "Calling the gc 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 Java Virtual Machine has made a best effort to reclaim space from all discarded objects."

      So, if the majority of the calls are more or less an empty function call, what's the harm in doing it?

      The VM can't determine whether a gc is useful or not without a full heap scan. AFAIK, calling System.gc() will usually result in a full scan, totally defeating the standard gc'ing (which is supposed to be efficient as is). You aren't supposed to call System.gc() except in special circumstances.

    22. Re:Um, it's online by Sinterklaas · · Score: 2, Insightful

      Calling System.gc() will usually result in a collection. The VM can't know whether a garbage collect will be useful, because only a full mark and sweep will reveal that. Thus, while the docs state that garbage collection will not necessarily happen after a call to System.gc(), all current VMs will do a full gc (AFAIK). That makes sense because the programmer can determine the need better than the VM.

      The JVM is designed to make most efficient use of the available RAM and calling System.gc() totally defeats that. To 'forbid' Java from doing it's thing is as fair as disallowing the C++ from using pointers, non-objects (except primitives) and other features which can't be found in Java. Obviously, that is wrong because those features make C++ what it is, just like (unforced) gc is an inherent part of Java.

      The only way to determine what the effects are of garbage collection vs (de)allocation is to design a benchmark specifically for this purpose. For instance, you could handle some big images and see how fast each language can complete the benchmark. Another interesting benchmark is to handle a large amount of small objects. However, in the end, the effect of garbage collection on real world apps can differ greatly, depending on:
      - the total amount of memory the app can use
      - the number of allocated objects
      - the size of objects
      - the lifetime of objects (Java is far more efficient with short-lived objects, for which it uses a mini-heap and mini-gc)
      - the workload of the app (can it do garbage collection during a time of low load?)

      The results can differ greatly depending on the particular situation that you are looking at. Of course, it is true in general that it is rare for a language to be better on all fronts, so you always need to look at what you want to do and how well the language is suited to do that. That is also the reason why I hate broad generalizations like:

      Sadly, I'm once again seriously disappointed in Java.

      Just because the benchmark is flawed, doesn't mean that Java was somehow bad. Especially since your benchmark was a thousand times more flawed. Since you have shown little knowledge about Java (every beginning Java programmer learns that you should avoid calling gc directly), I suggest you stop making these stupid comments. /end rant

    23. Re:Um, it's online by sploxx · · Score: 2, Interesting

      Heh, it's funny, just yesterday, Bjarne Stroustrup himself gave a lecture at our university!

      He spoke *a lot* about 'efficiency', and IMHO, he did have a valid point. He compared C++ to C and FORTRAN and made good arguments why C/Fortran is slower than highly optimized C++ code nowadays (Because of the amount of information a C++ compiler can collect about the program's structure... in C everything is flattened to a low level by the programmer already and information is lost for the compiler).

      Asked after his lecture if there are plans for a virtual machine for C++ (as an *alternative* to native code), Mr. Stroustrup strongly denied that. I think this is one of the more important reasons why Java is considered 'better' by many people. Because it *seems* that, with the VM, it's more portable. There is clearly not engineering reason for a C++ VM, but politically, it would give C++ the opportunity to gain ground against Java.

      You have to, of course, use appropiate C++ paradigms, like templates emulating lazy evaluation etc. A "naive" matrix class in C++ is nice to write, but not very efficient to use.

      Even if you cry out loud that efficiency doesn't matter any more, it's, at least somewhat, wrong. It's an arrogance of the programmers against the users of their programs. If one programmer saves 10 hours of time but for each user, using the program takes 10min longer (be it startup times or whatever), it's time-inefficient if only 100 people are using the program. And you have to take into account that the time of the users adds up more easily than that of the programmers. They're probably not running the program once, but multiple times...

      Of course, java has it's uses, e.g. client-side interfaces running in the browser.

      But the argument, stated over and over again, that Java is/can be faster because of runtime optimizations, is *really* flawed and just ignoring facts. There are compilers which can do optimizations on profiling data from the actual running program. Beat that java. A compiler tailored to the machine *and* the beloved runtime optimizations.

    24. Re:Um, it's online by nikster · · Score: 2, Insightful
      I'm seeing the benchmarks take serious advantage of java's GC mechanism
      the first part of your analysis is sound: the benchmarks are highly questionable since the Java code never runs the gc, thereby cheating it's way out of having to do mem management.
      very good point.
      Worse, when I ran it with a 1:1 ratio of delete:System.gc(),
      so, you took it back to Java, and biased the test in favor of C++ by running way too many gc's, which, as you point out don't even mean anything because the gc doesn't get invoked immediately. by adding System.gc() to the Java side of the test, you in fact added some kind of randomizer to the code. you don't know what System.gc() does - it's a notification that the gc may run, yes. But you don't know what exactly the system will do after it's called. For all you know, it could stall for a couple of seconds. Or it could count all objects in memory. Or... anything. You added a random delay to the Java side of things.
      and, lo and behold, you "proved" that c++ is faster. now, if the original comparison was biased, this was surely worse.

      a better test would probably be to let the c++ side never collect anything. and to stop the watch before java starts collecting (just use a huge max. heap size and set it to use the traditional gc and it won't collect anything for a while).

      Regarding the article: It's kind of silly to count the JVM startup delay in the tests. Because for some things it will matter, e.g. programs that get run, then shut down again zillions of times. That's why you can't write command line tools in Java. For other things it won't matter at all because they get started once and then continue running (client-GUI software, server app). Also, new JVMs from Apple (and Sun, in the future) just won't have the startup delay because they will statically link precompiled versions of the java class library (rt.jar).

      IMHO, speed matters only in one area: When doing calculations in tight loops. There, i believe Java is just as good as c++ because the hotspot compiler actually works and will generate fast, optimized assembler code out of the java loop.

      I did some unrelated speed tests within Java (checking the overhead of final method calls - it turned out to be zero as it gets optimized away) and found out, to my surprise, that a simple calculation in a for-loop ran at 400 million loop iterations per second, or 1/3 of phyiscal machine speed (1.3GHz Pentium-M). I found that impressive. Come to think of it, it was probably exactly the DRAM access speed (i was accessing a huge array).
    25. Re:Um, it's online by cookd · · Score: 2, Interesting

      Most of what you said is very true. But things went downhill in the last two paragraphs.

      Efficiency matters, but sometimes it doesn't come in the obvious ways. To set the tone, here are a few examples.

      The Bubble sort takes only a few lines of code and has no significant memory requirements. A QuickSort takes 50 to 100 lines of code and uses a recursive algorithm requiring a stack of some sort. Yet for some reason many applications choose the QuickSort.

      Virtual memory imposes a huge performance penalty on the system. Every memory access has to be translated into the physical address. Page tables take up a significant percentage of RAM. They complicate systems programming significantly. And somehow we would never dream of designing a serious system without virtual memory. And even after adding a FOURTH level of page tables, somehow the AMD64 is able to outperform the two and three level 32 bit chips.

      Running software at different privilege levels introduces a huge penalty of context switching. An OS call, which cost only 4 to 10 cycles under DOS, now costs 1000 to 3000 cycles under a "modern" OS. Why would we actually prefer such gross inefficiencies?

      Instead of setting up a direct cable link for data transmission across the US, which would create a direct link of only 3000 miles, many industries find it more efficient to sent the data 52,000 miles into space to have it bounced back by satellite.

      The fastest way to get a missile from here to Russia is also via a trip into space.

      What I'm trying to get at is that there are a lot of cases where the best solution looks wasteful until you get the big picture. You and I understand how a 4 level system of page table lookup can end up outperforming even a direct memory access scheme for some tasks, how kernel/user mode is a significant and necessary part of modern programming, even at the huge cost it adds to system calls, and how going the "long way" can be faster than the more direct route. So don't be afraid to consider alternatives that don't appeal to you at first glance.

      So you don't like Java and other inefficient VM-based systems, and you don't believe that it can be faster? Yes, there are many systems for analyzing runtime behavior and using that data to perform static optimizations. But there's no reason Java can't apply those same optimizations. On the other hand, there are optimizations that Java can do that you CAN'T do with static code. For example, Java can inline a function across a shared-library boundary (this is a HUGE win). Java can remove expensive security access checks for an application that is already running at full trust level. Java can optimize the generated code for the current processor - Pentium 1 through 10? SIMD? Super-SIMD? MMX or no? Floating point? All of these cases can be handled really well by Java, and it can pick the instruction mix that matches your system perfectly. The static code generator has to make some compromises. You can load a different DLL for each processor, but honestly you can only distribute so many flavors of your library... and they'll be obsolete the next time Intel decides to change its optimization strategy. Running on a single proc system? You can seriously simplify your synchronization primitives, saving a LOT of cycles on multithreaded code. Lots of memory? Java can trade space for speed. Tight on memory? Java can trade speed for space. And it can change its mind from day to day, depending on what other apps you have running. The list goes on and on. Not all of the above optimizations have been implemented in production JVMs yet, but they have all been researched, and they aren't theoretical -- there are real performance tests that show they can make a difference. They just need a few more years to be built into the next generation of VMs.

      A few other areas that people often don't think about: Bytecode is usually significantly more compact than the resulting machine code, especially on RISC chips. Throw in

      --
      Time flies like an arrow. Fruit flies like a banana.
    26. Re:Um, it's online by netstat · · Score: 2, Insightful

      The garbage collector runs in a low priority thread. If you just run some code that is doing nothing but calling System.gc(), then of course it will be called. However, if your code is actually trying to do something else, it really is just a "hint" as the other poster stated.

    27. Re:Um, it's online by GooberToo · · Score: 2, Interesting

      It doesn't say that at all

      I wish I could find what I originally read. It stated that it simply issued a request for the gc to collect. Under a high load (tight loop, in this case), chances are, the gc will not collect. Accordingly, I have no problem finding many posts by "java gurus" which seem to be under the same impression I am (that clearly doesn't make it true though). Also, even here, others have piped in and offered that gc is run in a low priority thread whereby, the "hint" is actually a mechanism which attempts to wake up the gc, assuming it's not already running. Thusly, while I do agree that calling System.gc() on a one to one basis is not fair (clearly not an apples to apples comparison), I'm still not convinced that simply calling System.gc(), and it returning, means that all memory has been collected.

      Regardless, I do believe I have a legitimate point and that these benchmarks are fundimentally flawed.

  2. The Great Computer Language Shootout by thebra · · Score: 4, Informative

    Correct link

  3. Yes but... by Anonymous Coward · · Score: 2, Funny

    how does it corner?

  4. Netcraft Confirms: by BandwidthHog · · Score: 3, Funny

    Fact: C++ is dying....

    Oh hell, I don't have the heart. Nevermind.

    --

    Quantum materiae materietur marmota monax si marmota monax materiam possit materiari?
  5. Anyone got a match? by nebaz · · Score: 5, Funny

    Here's some kindling...

    vi is better than emacs
    bsd is better than linux
    gnome is better than kde
    .
    .
    .
    anything else?

    oh yeah...
    my dad can beat up your dad.
    And you smell funny.

    --
    Rhymes that keep their secrets will unfold behind the clouds.There upon the rainbow is the answer to a neverending story
  6. meh by jnapalm · · Score: 2, Funny

    i tried to get first post with my C++ autoposting application...but its too damn slow.

  7. What are -client and -server? by JoshuaDFranklin · · Score: 4, Informative
    1. Re:What are -client and -server? by Jennifer+E.+Elaan · · Score: 4, Informative
      "Some of the other differences include the compilation policy used, heap defaults, and inlining policy."

      Am I the only one who noticed the "inlining policy" thing? Considering "method call" was one of the most compelling arguments for his case (by orders of magnitude!), the fact that the methods being "called" are being called *INLINE* should mean something.

      If you're allowed to turn on the java inliner, surely you can spare the time to turn on the C++ one as well (he used -O2, not -O3, for compiling the C++ apps).

    2. Re:What are -client and -server? by Anonymous Coward · · Score: 3, Interesting
      Am I the only one who noticed the "inlining policy" thing? Considering "method call" was one of the most compelling arguments for his case (by orders of magnitude!), the fact that the methods being "called" are being called *INLINE* should mean something.

      If you're allowed to turn on the java inliner, surely you can spare the time to turn on the C++ one as well (he used -O2, not -O3, for compiling the C++ apps).

      It does mean something. However, here's something a little odd about the differences between C++ and Java: in C++, the compiler makes the decision about what to inline before it fully knows what is calling what. That is because the compiler runs before the linker. So C++ is working with more limited information. Meanwhile, the Java virtual machine has everything integrated. The compiler (the JIT) and the linker (the class loader) and the loader (also part of the class loader) run all together and can cooperate and communicate.

      Why is this important? Because the C++ compiler must make all kinds of guesses when it makes these optimizations. If you have a 1-line function, it probably makes sense to inline it in every place it's called, because the speed will increase and the code size won't (the inlined code will probably be smaller than the code to make a function call). But say you have a 25-line function. Should you inline this? If it's called only in one place and nowhere else, it's still more efficient. But if it's called in 50 places, you waste a lot of space by making 25 copies of the function. So maybe you should inline it only in the one or two places where it counts. OK great, but which two places are these? The C++ compiler is left having to just guess. The Java virtual machine can instead just observe the program as it runs and *know* where inlining is worth it and where it isn't.

      Also, what if you have a really small function in a library and you want to inline that? Well, in C++, if you dynamically link to that library, you *can't* inline the function. It's just not possible. But with Java, you can, because it's all just classes that are loaded by the class loader and then translated into machine code as needed. So you can inline functions that come from dynamic dependencies, like system libraries.

      And then, as someone else said, Java can even inline virtual method calls! How can it do this? Again, by observing the conditions the code is *actually* executing under, not by theorizing about all possible conditions it might execute under. C++ has to allow for the possibility that every object is a different class and so must use a v-table. But Java can, in theory at least, know that while the object *could* be an instance of class X, Y, or Z, in reality the class loader has only loaded class Z, so therefore all instances must be instances of class Z. Presto, inlining is possible, at least until class X or class Y is loaded. But then, since the code is generated dynamically, when you load class X or Y, you could trash the inline code you generated and start over with virtual method calls now that you are having to plan for a different situation.

      I should point out that you can get 99% of these performance boosts in C++ by hand-tweaking your code. You can figure out which methods need to not be declared virtual and remove the "virtual" keyword from those methods. If you need to make an inline call to some function in a system library, you can manually copy the code from that library into your source code and call it, as long as you're willing to rewrite and rebuild your C++ app when the library code (that you copied) changes. So these things are theoretically possible, but they are such a code maintenance and system administration nightmare, that they are virtually always far from practical. But with Java or other similar languages, they can all happen for you automatically behind the scenes.

  8. He used g++ to compare C++ with Java... by exp(pi*sqrt(163)) · · Score: 4, Insightful

    ...on x86? Please! Wake me up when someone who knows enough about C++ to pick a decent x86 compiler runs some benchmarks.

    --
    Doesn't it make you feel good to know that our freedoms are protected by politicans, lawyers and journalists.
    1. Re:He used g++ to compare C++ with Java... by crawdaddy · · Score: 2, Funny

      You really see a difference in the infinite-element circuit simulators, though. That's probably what he's referring to.

    2. Re:He used g++ to compare C++ with Java... by ky11x · · Score: 5, Informative

      g++'s goal is modularity for ease of porting in cross-platform cross-compiling. aggressive optimization is not one of its strengths. the point of such benchmarks is really not a language comparison, but a comparison between the code generated by the most optimized compilers for that language on a specific platform. Using g++ for this simply causes the study to lose credibility

    3. Re:He used g++ to compare C++ with Java... by exp(pi*sqrt(163)) · · Score: 4, Informative

      g++ isn't great at optimizing. For code I write it's somewhere between 0 and 50% slower than MSVC. It depends a lot on the type of code of course. For pure numerical work I think the Intel compiler usually scores highly so I'm surprised you're not seeing much difference.

      --
      Doesn't it make you feel good to know that our freedoms are protected by politicans, lawyers and journalists.
    4. Re:He used g++ to compare C++ with Java... by cyfer2000 · · Score: 2, Insightful

      "Hi, I am a professor from X university, and I was wondering if we could get a license of your compiler for research?"

      "I am sorry, blah blah blah..."

      "May I talk with your boss?"

      "Sure, just a second...du...du..."

      "Hi, can I help you?"

      "Hi, I am a professor from X university, and I was wondering if we could get a license of your compiler for research?"

      "Ah...May I know your research topic?"

      "It's about the speed of C++ and java...blah blah blah"

      "As a company sponsored a lot of research, you know, we'd like to support your research, but, you know...blah blah blah."

      "So how much it could be?"

      "something between your arm and your leg"

      "I am going to think about it, thank you for your help, have a nice day"

      "you too, feel free to contact us, bye."

      "Bye"

      "OK, boy, we use gcc firstly, and after we got enough funding, we may buy a better compiler!"

      "Yes, sir, and the result of GCC is here."

      "Nice..."

      --
      There is a spark in every single flame bait point.
    5. Re:He used g++ to compare C++ with Java... by vlad_petric · · Score: 2, Informative
      Try inter-procedural optimizations. For that you have to give icc/icpc the -ipo flag, and furthermore use xiar instead of ar and xild instead of ld.

      The results might shock you.

      --

      The Raven

    6. Re:He used g++ to compare C++ with Java... by mwillis · · Score: 5, Informative

      Intel gives their c++ compiler away free for non-commercial hobbyist use on linux.

      The windows version has a free trial that runs for 30 days.

      Try it. See if it makes a difference. If it doesn't, torch it. If you find it makes your critical code run 2x faster, then... have a look at what a computer that runs 2x faster will cost you, and then decide what to do.

    7. Re:He used g++ to compare C++ with Java... by CoughDropAddict · · Score: 3, Informative
  9. Re:If you don't run the JVM... by Tar-Palantir · · Score: 4, Informative

    He claims you should use the server JVM instead, stating that it is faster but slower to startup and consumes more memory.

  10. Cross platform by leakingmemory · · Score: 2, Informative

    Java's strength is mostly it's cross platform compatibility. I have never really liked C++ very much. It seems complicated to write cross-platform code with C++. (Header troubles, and all OSes seems to have it's own implementation. Ie. try to compile Linux code on FreeBSD, and opposite) As a conservative coder I therefore prefer C, which is as fast as you (the coder) make it.

  11. Re:Caught up with the speed, but still the ugliest by mhale2243 · · Score: 3, Informative

    True, which is why the eclipse project (www.eclipse.org) created and maintains SWT. A portable native widget tookit. See http://www.eclipse.org/articles/Article-SWT-Design -1/SWT-Design-1.html for more info.

  12. Languages vs Compilers by Anonymous Coward · · Score: 5, Insightful

    Java and C++ are language. Languages aren't "faster" or "slower", but compilers for them might be. I find it somewhat underhanded to put the languages in the header when it's really comparing compilers.

    Not to mention, inter-language compiler benchmark[et]ing is notoriously difficult to get 'right'. The programs tested are often stupid (doesn't do anything meaningful), or constructed by a person with more skill/bias for one language than the other.

    1. Re:Languages vs Compilers by ms139us · · Score: 2, Funny

      Languages aren't "faster" or "slower"

      Thank God, finally someone understands! I was recently benchmarking Turtle Logo against some highly optimized Opteron-specific assembly code for an application that calculates PI to the 400,000th digit.

      I was surprised to see that Logo was slower, but I think I just didn't optimize it enough. I am tuning the Logo floating point code right now, and Logo should stomp the hell out of the assembly code "Real Soon Now."

  13. Re:my arse by kaffiene · · Score: 3, Funny

    "My arse" is a good name for this post since that's obviously where your head is stuck - much like the rest of the /. morons with their anti-java-no-matter-what stance.

    I used to be a C hacker and a laughed at Java when it came out because of it's poor performance. Times have changed, but the language bigots haven't.

  14. Nice to hear... by twocoasttb · · Score: 4, Insightful

    It's been ages since I've programmed in C++, but it's good to know see these favorable comparisons. I think about the Struts/Hibernate/Oracle applications I write today and shudder when I imagine what how difficult it would be to have to develop web applications in C++. C++ will be around forever and certainly has its place, but long live Java.

    1. Re:Nice to hear... by drew · · Score: 3, Funny

      I think about the PHP/PostgreSQL applications I write today and shudder when I imagine what how difficult it would be to have to develop web applications in Java...

      --
      If I don't put anything here, will anyone recognize me anymore?
  15. Re:Sorry, no. by Ianoo · · Score: 4, Funny

    I think you're missing the point. I bet 19 seconds of that execution time was the start-up and shutdown of the virtual machine. As the program gets bigger and bigger, this becomes less and less significant.

  16. Re:Caught up with the speed, but still the ugliest by mark-t · · Score: 4, Informative
    You haven't played with the pluggable look and feel for Swing much, have you?

    Oh... and as of Java1.5, Swing apps can now be skinned to look however you'd like them to.

  17. A few points... by mindstrm · · Score: 5, Insightful

    There seem to be some unanswered questions here..

    - How equivalent were the benchmarks? Where they programmed in an optimum way for their respective compilers and libraries? I'm sure the java ones were.. what about the C++ ones? The author states he doesn't understand G++ very well.

    G++ is also known to not produce the best results.

    "I rant it with -O2"

    My guess is many of the tests were not implemented properly in c++.

    The main clue would be this... I can understand java having better than expected performance.. but there is no way I can accept that java is that much FASTER than properly done C++... it doesn't make any sense.

    1. Re:A few points... by Trillan · · Score: 4, Insightful

      Maybe it does make sense. But what it proves is that C++ (at least as implemented by GCC, but it's probably a design flaw) is slower than expected, not that Java is blazingly fast.

    2. Re:A few points... by maraist · · Score: 2, Insightful

      Except that in enterprise computing (as opposed to scientific computing), we are not interested in JUST throughput, but more often the time-to-shipment of the application, and the robustness of the code. Robust code is often abstracted or is littered with superfelous code (i.e. redundant checks for nullity).

      Code that is easy to read, easy to maintain is often not very performant, because you aren't allowed to make special-case optimizations at the code level, since they are often a nightmare for other's to interpret.

      In terms of efficient elegant code, it is trivial to use a hash table over a linked list in java (in fact, linked lists are harder to implement). Thus a LOT of java code uses such O(k) algorithms. On the other hand, in c it's relatively easier to use bitmaps than a hashed set, and thus c has less overhead for a common practice. But, as a consequence, bitmaps often have an upper-bound (no more than 32 entries) (yes, I know you can use bitmapped c structures). But a hash table is easier to read and harder to screw up than a boolean-logic bitmap, so it is often a better choice for "enterprise code".

      So my response is that it depends on how you define "efficient programming". Do you mean efficient execution (which really is optimized programming), or efficient writing and maintanance of code. I suspect you mean the former, but what you should mean is the latter.

      What's more, as far as a business man, you have to weigh the cost of development time v.s. performance of application. Well written non buggy, easily adaptable code requires little future man hours, and can take advantage of moore's law. If the software is successful, "scaleable" code can run on ever more expensive hardware (clustering). Highly optimized software may not be easily clusterable, or may not lend well to adaptations; each adaptation would require re-optimizing the code. The classic example here is Java's "Reflections", where a text configuration file is often used to link unrelated code together. I see this a lot in databases where we map new tables to code which may or may not be a proper fit.. The reflective configuration handles the remainder of the impedence mismatching. Note that you can do this in c as well, but it wouldn't be the fastest solution by far.

      --
      -Michael
    3. Re:A few points... by Cthefuture · · Score: 5, Interesting

      I've been playing with those benchmarks for ages. I use them any time a new language comes out or if I just want to do some independent testing.

      A couple points:

      - The "Great Shootout" benchmark times are sometimes way off because the run-time was too short to get an accurate reading. In those cases the tests should have been run with higher values to really stress the machine. That doesn't appear to be an issue in this test though (assuming his graph values are in seconds).

      - Many of the C++ tests are not optimized. That is, they use C++ features like the iostream stuff (cout, and friends) which is extremely slow. The C versions are available and very fast. C++ is pretty much just an extension of C. You don't need to use C++ features if they slow you down. Another one is the hash stuff. In the C++ hash benchmark there are some goofy mistakes made by using the brackets [] operator where it forces several unnecessary lookups. You can also substitute a better STL hashing function that is faster (like MLton's insanely fast hasher).

      - The test could be done by comparing C to Java. Anything in C++ can be made as fast as an equivalent C version but there are not many programmers that know how. Just assume anything in C++ will run as fast as a C version, and if it doesn't then you did something wrong. The hash tests would be easier in C++ though. If they were written properly they would kill the Java version.

      With that said, I'm going to try these tests myself because I do not believe the results to be accurate. but who knows...

      --
      The ratio of people to cake is too big
    4. Re:A few points... by GooberToo · · Score: 2, Insightful

      but there is no way I can accept that java is that much FASTER than properly done C++

      Well, bluntly, you need to better understand the technology so you can adjust your expectations. While I've only started looking at the code, it does appear that these benchmarks represent many ideal situations whereby java's hotspot technology can make many aggressive optimizations.

      These benchmarks, by no stretch of the imagination mean that Java is faster than C++. It does, however, clearly show that in ideal situations, hotspot can clearly make huge leaps in performance.

      Worth noting, psyco for python (a hot-spot "like" technology), also has ideal situations where it actually performs faster than c. Again, this is because it's able to more aggressively optimize in certain situations with more knowledge than the compiler had during compilation. Does this mean that, in whole, python+psyco is also faster than c? Of course not. But, it certainly does lend support to the notion that java and it's hot spot technology can not be dismissed out right, as I see many racing to do.

      The big question, which I currently do not have an answer to is, do these benchmarks have any meaning in the least, in the real world? If so, in what situations do they reflect?

      In stead of panicing about these results, let's take them for what they are, lick on a grain of salt whlie we're at it, and figure out if they mean anything in the real world. I suspect that they don't, but that's just my bias talking. In the mean time, I'm going to be looking at some code.

  18. Could use a good analysis by GillBates0 · · Score: 5, Interesting
    The results are very non-intuitive. An extra layer between the program -> CPU implies an extra amount of overhead - be it any layer (VM at the Application layer, VM at the OS layer, or even at the CPU layer (hyperthreading)).

    I looked at his results page quite extensively, but failed to find a good analysis/justification of the results. Just saying that the Server JVM is better than the Client JVM is *not* enough.

    I want to know where the C++ overhead comes from, which Java manages to avoid - does the JVM do better optimization because it is given a better intermediate code (bytecode)? Is it better at doing back/front end optimizations (unlikely given gcc's maturity).

    I tried to look for possible discrepancies in the results, but the analysis will definitely take more time - and I think it's the job of the experimenter to do a proper analysis of the results. Liked his choice of benchmarks though.

    --
    An Indian-American Hindu committed to non-violent thought/speech/action alarmed by the global explosion of radical Islam
    1. Re:Could use a good analysis by Magnus+Pym · · Score: 2, Informative

      I agree with you. This does not match my experience at all. The Java programs I have used (especially anything with a GUI) have been bloated and much slower than programs in C++ that do 10 times as much. I would be curious to see if these benchmarks included things like opening windows, pulling down menus etc.

      Magnus.

    2. Re:Could use a good analysis by cduffy · · Score: 2, Insightful

      Well, yes, but the GUI issues are something completely different -- specifically, that Sun has no clue how to write a decent widget set, and insists on going either too far in one direction (AWT -- only supplying widgets available natively on every supported platform) or too far in another (Swing -- emulating every widget even on platforms where they're available natively).

      These benchmarks *didn't* include things like opening windows and so forth, and I think that's appropriate. Anyone who cares about writing a graphical Java app with decent performance should be using a different widget set anyhow, like IBM's SWT.

    3. Re:Could use a good analysis by jfengel · · Score: 5, Interesting

      His examples are all non-GUI things; they're pure CPU benchmarks. That's one major case where Java is certainly slower than C++.

      Most of his tests are big loops (primes, string concatenation, etc.) These are cases where (as a sibling poster mentioned) hot path analysis can do you a world of good. A heavily tuned C++ program can do it just as well, or better, but the point of using a high-level language is that you don't have to do those optimizations yourself; you write the code in whatever way seems natural and you let the compiler optimize.

      In a long-running Java program, you don't have that extra layer between the program and the CPU. The JIT does a real native compilation and passes control off to it. Once that's started, it runs just as fast as any other assembly code. Potentially faster, given that the JIT can look at the current run and optimize based on the way the code is going: the precise CPU it's running on, where things are in memory, how far it can afford to unroll a loop, what loop invariants it can lift, etc. It can even replace code as it runs.

      The question then is, does the one-time (albeit run-time) optimization do more good than it costs?

      That's especially easy on a hyperthreaded system. In a C++ program, these loops will run in a single thread on a single CPU, so if the JIT compiler runs on the other (virtual) CPU, you get its effort for free. Even the garbage collector can run on the other CPU, so you get the convenience of memory management with no total performance cost. (You do burn more CPU cycles, but you use up no extra wall-clock time.)

      GCC is very mature, but it doesn't have the option of changing the code at run time. Especially on modern CPUs with their incredibly deep pipelines, arranging your code to avoid pipeline stalls will depend a lot on runtime considerations.

      Also, Java has a few advantages over C++ in optimization. It's very easy to analyze Java programs to be certain that certain memory locations absolutely will not be modified. That's much harder in languages with native pointers. Those invariants allow you to compile out certain calculations that would have to be done at runtime in a C/C++ program. You can even start spreading loop cycles over multiple CPUs, but I'm pretty certain that the present JVMs aren't that smart.

      These results are toy benchmarks, and not really indicative of real performance, even on purely non-GUI code. But I wanted to outline the reasons why the results aren't just silly, and they do have a theoretical basis.

    4. Re:Could use a good analysis by Paul+Lamere · · Score: 2, Informative
      One of the papers cited on the page is the FreeTTS FreeTTS - A Performance Case Study a paper written by the speech team here at Sun's Research Labs.

      This paper describes the performance issues we encountered when developing FreeTTS. I think it is a pretty good representation of the issues involved in developing a high-performance Java application along with a comparision between a Java and a native-C version of the same application. This paper describes how we ported a native-C synthesizer (Flite) to Java (FreeTTS) and how were able to get better performance from our engine.

      This is not a toy application but a real application that performs well in a domain where performance really matters.

  19. Re:Caught up with the speed, but still the ugliest by saden1 · · Score: 4, Insightful

    I’m sorry but someone who says "I've never been very good at decoding GCC's error messages" is not competent enough to perform performance comparison. This performance test is a shame and shouldn’t be taken seriously.

    --

    -----
    One is born into aristocracy, but mediocrity can only be achieved through hard work.
  20. That just means... by SuperKendall · · Score: 2, Interesting

    You were running Swing with the Windows L&F.

    --
    "There is more worth loving than we have strength to love." - Brian Jay Stanley
  21. Expert results by otterpop81 · · Score: 5, Insightful
    Some of the C++ tests would not compile. I've never been very good at decoding GCC's error messages, so if I couldn't fix a test with a trivial modification, I didn't include it in my benchmarks.

    That's Great! I can't figure out GCC's error messages, but I offer definitive proof that Java is faster than C++. Nice.

    1. Re:Expert results by Xugumad · · Score: 4, Interesting

      Also, a quote from the article:

      "I was sick of hearing people say Java was slow, when I know it's pretty fast"

      Nice, unbiased viewpoint there...

    2. Re:Expert results by drew · · Score: 2, Funny

      you didn't even have to go that far to see his bias... just take a look at the title:

      The Java is Faster than C++ and C++ Sucks Unbiased Benchmark

      --
      If I don't put anything here, will anyone recognize me anymore?
  22. Re:Just one game by Mindcry · · Score: 2, Informative

    unreal uses a java like scripting language, but its for gameplay code, not the actual rendering, however, i think that's as close as it comes right now. (the java like stuff is something like 20x as slow as the c++ code, cause of the overhead etc)

    P.S. a lot of gameplay code is also in c++ and compiled into dll's (i believe), but mods dont have access to the headers to compile c++ code into the game readily.

  23. Re:This doesn't make any sense... by Ianoo · · Score: 4, Informative

    Java isn't "emulation". Modern JVMs use a JIT (just-in-time compiler) to translate bytecode instructions into pure binary assembled object code just before it is reached in the program (hence "just in time"). This is cached, so the next time that particular code is executed, it will run at full assembler speed.

    Something I've often wondered is whether this caching could be persistent, i.e. be kept between runs of the JVM. Eventually, the entire program would be translated to pure assembler with the cost of translation largely amortised across many sessions. You still keep the safety, cross platform compatibility and ease-of-programming of a bytecode language (i.e. Java, C#) but you get the bonus of the cached object code being just as fast, even during startup and shutdown.

  24. Re:Sorry, no. by kaffiene · · Score: 2, Insightful

    You're measuring startup time, not execution speed.

    Duh.

  25. I don't actually care hugely about performance by Omnifarious · · Score: 5, Interesting

    I care that Java is an inconvenient pain to develop in and use. I care that I have to start a mini-OS just to run a Java program. I care that the language is under the control of one vendor. I care that the 'intialization == resource allocation' model doesn't work in Java. I care that the type system is too anemic to support some of the more powerful generic programming constructs. I care that I don't get a choice about garbage collection. I care that I don't get to fiddle bits in particular memory locations, even if I want to.

    I think Java is highly overrated. I would prefer that a better C++ (a C-like memory model, powerful generic programming, inheritance, and polymorphism) that lacked C++'s current nightmare of strangely interacting features and syntax.

    I use Python when I don't need C++s speed or low-level memory model, and I'm happier for it. It's more flexible than Java, much quicker to develop in, and faster for running small programs. Java doesn't play well with others, and it was seemingly designed not to.

    Besides, I suspect that someone who knew and like C++ really well could tweak his benchmarks to make C++ come out faster again anyway. That's something I've noticed about several benchmarks that compare languages in various ways.

    1. Re:I don't actually care hugely about performance by Bullet-Dodger · · Score: 3, Interesting
      I think Java is highly overrated. I would prefer that a better C++ (a C-like memory model, powerful generic programming, inheritance, and polymorphism) that lacked C++'s current nightmare of strangely interacting features and syntax.

      Have you looked at Objective-C? I'm not an expert, but it sounds just like what you describe. As a downside though, I'm not sure how well supported it is on non-OS-X platforms.

    2. Re:I don't actually care hugely about performance by Xetrov · · Score: 2, Informative

      Converting objc -> c is trivial -- There are a number of objc -> c converters.

      Actually I think that might be how most of the compilers actually work :)

      So if you like Objective-C and would rather code in it... you can!

  26. Re:Caught up with the speed, but still the ugliest by C.+E.+Sum · · Score: 3, Informative

    One of the best things about OS X is Aqua-ized Java apps.

    http://developer.apple.com/documentation/Java/Co nc eptual/Java141Development/UI_Toolkits/chapter_5_se ction_2.html

    --
    -- Have you ever imagined a world with no hypothetical situations?
  27. Flawed Test by Emperor+Shaddam+IV · · Score: 3, Insightful

    Comparing one C++ compiler (gcc) against the Java JVM on one operating system is not much of a test. I love Java, but this is almost something like microsoft would do. Test one specific OS, compiler, and configuration, and then make a blind, far-reaching statement. A fair test would include several platforms and compilers.

  28. Some problems I had using Java by Anonymous Coward · · Score: 2, Funny

    I don't want to start a holy war here, but what is the deal with you Java fanatics? I've been sitting here at my freelance gig in front of a Java program (running on a PIII 800 w/512 Megs of RAM) for about 20 minutes now while it attempts to copy a 17 Meg file from one folder on the hard drive to another folder. 20 minutes. At home, running an equivalent Visual Basic program on my Pentium Pro 200 with NT 4, which by all standards should be a lot slower than this Java program, the same operation would take about 2 minutes. If that. In addition, while it is running, Netscape will not work. And everything else has ground to a halt. Even jEdit Lite is straining to keep up as I type this.

    I won't bore you with the laundry list of other problems that I've encountered while working on various Java programs, but suffice it to say there have been many, not the least of which is I've never seen a Java program that has run faster than its VB counterpart, despite Java's faster runtime system. My 486/66 with 8 megs of ram runs VB programs faster than this 800 mhz machine runs Java at times. From a productivity standpoint, I don't get how people can claim that Java is a "superior" language.

    Java addicts, flame me if you'd like, but I'd rather hear some intelligent reasons why anyone would choose to use a Java over other faster, cheaper, more stable systems.

    1. Re:Some problems I had using Java by ky11x · · Score: 2, Funny

      You, sir, are inspired. I applaud this wonderful transformation of the Mac troll into a Java troll. I'm sitting over here laughing so hard my nose hurts.

  29. One example of why the tests are BS by mypalmike · · Score: 5, Insightful

    From methcall.cpp:

    int
    main(int argc, char *argv[]) {
    int n = ((argc == 2) ? atoi(argv[1]) : 1);

    bool val = true;
    >> Toggle *toggle = new Toggle(val);
    for (int i=0; i<n; i++) {
    val = toggle->activate().value();
    }
    cout << ((val) ? "true" : "false") << endl;
    delete toggle;

    val = true;
    NthToggle *ntoggle = new NthToggle(val, 3);
    for (int i=0; i<n; i++) {
    val = ntoggle->activate().value();
    }
    cout << ((val) ? "true" : "false") << endl;
    >> delete ntoggle;

    return 0;
    }

    Why allocate and deallocate an object within the scope of a function? Well, in C++, there's no reason, so this is bad code. You can just declare it as a non-pointer and it lives in stack space. But guess what? You can't do that in Java: all objects are allocated on the heap.

    That, and using cout instead of printf, are probably why this is slower than the "equivalent" Java.

    -_-_-

    --
    There are 0x40000000 types of people: those who understand 32-bit IEEE 754 floating point, and those who don't.
    1. Re:One example of why the tests are BS by andy55 · · Score: 2, Informative
      Why allocate and deallocate an object within the scope of a function?

      You would do it if you need a scrap object only sometimes (and didn't want to pay the overhead penalty of instantiating it every time the proc got called). Here's an example:


      void foo() {
      ...
      if ( SomeRareCondition() ) {
      AReallyNastyObject* temp = new AReallyNastyObject;
      ...
      delete temp;
      }
      ...
      }

    2. Re:One example of why the tests are BS by halosfan · · Score: 2, Interesting

      The point he's making is that the C++ code is poorly written, and that might well affect benchmarking.

      Also, if the activate function is virtual (no way to avoid it in Java), this is a runtime vtable lookup in the loop, whereas for a statically allocated object the address of the function would have been fixed at runtime. Granted, the cost is probably negligible to that of activate's implementation, but (a) it's impossible to know without actually profiling the code, and (b) the activate()'s implementation is likely to be as poorly written as the code that calls it.

      Of course, all of this implies I was too lazy to actually look at the activate()'s code...this is Slashdot after all...

      --
      My only problem with Microsoft is the severity of bugs in their software.
    3. Re:One example of why the tests are BS by Bloater · · Score: 3, Informative

      The cout is done twice, and the new and delete are each done only once. They are not the reason for the poor performance.

      The problem is that g++ probably does not optimise it all inline, whereas the particular java VM he has chosen to use probably does.

      Although defining the Toggle variables with auto storage class may give g++ the hint it needs to realise this.

      Additionally, the activate method is declared to be virtual, this shouldn't be a problem, except that it may further hide the optimisation opportunity from g++. Note that the description of the test does not stipulate that it is testing virtual methods.

    4. Re:One example of why the tests are BS by ChaosDiscord · · Score: 2, Insightful
      You would do it if you need a scrap object only sometimes (and didn't want to pay the overhead penalty of instantiating it every time the proc got called).

      If it's C++, you can scope the variable to the block you need it in. The object should not be instantiated until (and if) the block is entered. C++ scoping fills me with more happiness than is probably healthy. The idiom "/* Read the file */; { FileLockObject thelock(filename); ReadFile(filename); }" is just so wonderfully clean. No matter how you exit the block (return, continue, break, throw), the lock is released immediately.

      Of course, your point is still valid. In more complicated functions you might have an object that is optionally created and must visible throughout a larger block or function. In that case, yes, you'd do exactly what you suggest. I've certainly done it myself.

      BigObject * tmp = 0;
      if(RareCondition()) {

      tmp = new BigObject;
      }
    5. Re:One example of why the tests are BS by boneshintai · · Score: 2, Insightful

      That's not useful.

      void foo() {
      ...
      if ( SomeRareCondition() ) {
      AReallyNastyObject temp;
      ...
      }
      ...
      }

      does essentially the same thing, but is less error-prone than an operator new/operator delete pair -- consider what happens if an exception occurs between your new and delete.

      There's basically no reason to allocate a single object using new and delete it within the same scope. Allocating arrays, or allocating an object for use in a different scope, are okay.

    6. Re:One example of why the tests are BS by rjh · · Score: 2, Insightful
      My prior message might not have shown why it's not wise to build a C++ iostreams implementation on top of the conventional C facilities. So let's try something nice and simple.
      char *foo = "Hello, World!\n";
      printf("%s", foo);
      Straightforward, right? So here's the question: when does the program figure out how to display foo?

      The answer is--at runtime. Printf takes two arguments, has to evaluate them, has to parse the format string, has to figure out how to splice the data into the format string, etc., etc. (Note that printf doesn't even know what kind of data you're giving it; it literally has to interpret the parameter list at runtime. That's the major performance problem with vararg functions.) Compare this to
      std::string foo("Hello, World!");
      std::cout << foo << std::endl;
      ... where, thanks to C++'s much superior type system, the C++ compiler knows at compile-time that foo is a string, and that allows the C++ iostreams facility to generate much better code than the C-style "let's figure everything out at runtime" way.

      Short version: a decent implementation of C++ iostreams will wipe the floor with C-style I/O. If you're seeing performance penalties from C++ iostreams, the first thing you should do is make sure the problem isn't in your own code; the second thing you should do is make sure your iostreams library isn't built on C libraries that determine type information at runtime.
  30. Re:my arse by kaffiene · · Score: 5, Informative

    *sigh* have you people never heard of runtime optimisations? There are some things you can optimise at runtime (like runtime constants) which are *impossible* to optimise at compile time.

    This whole "x is written in y, so x can't be faster than y" rubbish is just that - rubbish.

  31. Provide link please! by 3770 · · Score: 2, Insightful

    Please point me to a source which verifies your claim.

    --
    The Internet is full. Go Away!!!
  32. Re:Sorry, no. by shadowmatter · · Score: 5, Interesting

    First, it's been known for awhile that Java is a poor performer when writing to the console, for whatever reason. Second, your Java timing probably include the time to startup the VM (not that this is wrong).

    If you have a program that runs for awhile (so the startup time is small compared to the time the program takes to run), and does not do intensive output to the console, then Java is a reasonable choice in my opinion. Combined with SWT, Java applications can be quite snappy (see Eclipse, Azureus), and the end user will probably never know the difference.

    - shadowmatter

  33. Some performance myths by vlad_petric · · Score: 5, Interesting
    First of all, g++ actually sucks big time in terms of performance. Intel C Compiler, with inter-procedural optimizations enabled, produces code that's almost always 20->30% faster than g++. I've actually once compiled C code with g++ and it was visibly slower than the same code compiled with gcc ... oh well.

    Now, regarding java performance ... Java isn't slow per se, JVMs and some apis (most notably swing) are. Furthermore, JVMs usually have a slow startup, which gave java a bad name (for desktop apps startup matters a lot, for servers it's hardly a big deal). Java can be interpreted, but it doesn't have to be so (all "modern" JVMs compile to binary code on the fly)

    Bytecode-based environments will, IMNSHO, eventually lead to faster execution than with pre-compilation. The reason is profiling and specialized code generation. With today's processors, profiling can lead sometimes to spectacular improvements - as much as 30% performance improvements on Itanium for instance. Although Itanium is arguably dead, other future architectures will likely rely on profiling as well. If you don't believe me, check the research in processor architecture and compiling.

    The big issue with profiling is that the developper has to do it, and on a dataset that's not necessarily similar to the user's input data. Bytecode environments can do this on-the-fly, and with very accurate data.

    --

    The Raven

  34. Re:every year this happens... by bckrispi · · Score: 3, Informative

    Ummm, wrong. The majority of java class libraries, and (significant parts, if not all) of the compiler are written in Java. There is, of course, some C++ for doing really low level stuff, but not the amount that you're implying.

    --
    Xenon, where's my money? -Borno
  35. Re:Nort really surprising by pclminion · · Score: 4, Insightful
    Talk about an unfair comparison... The C++ example uses the standard IO library, while the C example uses the UNIX write() call. Of course there's going to be overhead associated with using a buffered IO layer.

    This would be much more meaninful if you had used fputs() instead of write() in the C version.

    As for "several orders of magnitude," I call bullshit. There's no way in hell the standard C++ IO functions are hundreds of times slower unless they're extremely badly written. Which leads me to another reason why this example sucks: there can be different implementations of the standard libraries.

    In conclusion, this "comparison" is a stinky pile of shit, and should be ignored. And it's not even on topic, since it doesn't have a Java version.

  36. C++ hash code is hobbled? by Sebastopol · · Score: 2


    Why did he use the strdup function when he already has the char array from the previous sprintf?? That step incurs a huge and unnecessary penalty w/an allocation, just pass the pointer!

    Also, in the second 'for' loop in hash2, he does extra work beacuse he already looked up (*k).second.

    shouldv'e done hash2[k->first] = k->second; ...to avoid another lookup penalty.

    Tell me I'm not crazy.

    --
    https://www.accountkiller.com/removal-requested
  37. been there, done that by Anonymous Coward · · Score: 5, Informative

    1) javac (Sun's Java compiler) is written in Java. You can even access it programmatically at runtime if you really want to.

    2) While it's not an id game, IL2 Sturmovik is a critically-acclaimed fight simulator that was written almost entirely in Java.

    1. Re:been there, done that by Midnight+Thunder · · Score: 2, Interesting

      Although I could only find this in regards to Java in the game, you'd be surprised how fast graphics can be in Java if you use the right graphics library. One which I have looked at is OpenGL for Java. It is essentially a Java language wrapper around the native OpenGL libraries. Given that more and more of graphics processing is done by the video card, then the graphics part of Java in this instance, would be as fast as your graphics card.

      --
      Jumpstart the tartan drive.
  38. Very true, if don't nkow what you are doing by Pac · · Score: 4, Informative

    Out of the box Swing is amazingly ugly. The people choosing default colors at Sun could well be substituted by a randomizer without a difference in results. I mean, who was the genius who thought purple bars in a menu were cute?

    Now, when you need to change that quickly and without much overload, there are ways. A little known global HashTable called UIDefaults lets you change just about everything on the visual interface without having to write your own LookAndFeel (which you obviously can do too, for very large projects). You can have your scrollbars, menus, etc in any colour, size and shape, using any font. You can easily change all default colours without having to set every control. After a while the ugliness ceases to be a problem.

  39. What about gcj? by joshv · · Score: 4, Interesting

    I'd be interested in comparing the speed of the native code generated by gjc to the that of JVM.

    -josh

  40. java *can* be fast... by alphafoo · · Score: 5, Interesting
    A year and a half ago I proposed building a standalone server-type application using Java, and my client scoffed at me because "everyone knows Java is slow". It was 1.4.2 on rh8.0 running on standard dual xeons. It ran pretty fast, and then I profiled it. Repeatedly. I replaced some of the stock library routines with my own faster ones or ones I found on sourceforge, found the most monitor-contentious areas and tuned them, played around with different GC strategies for the given hardware, and ended up with something that is amazingly fast. Scaled to 400+ HTTP requests per second and over a thousand busy threads, per node. Some of the speed bumps came for free, like when NPTL threads came available in the 2.4 kernel.

    I am starting on a new standalone server now doing something different, but I am going to stick with Java, and will be happy to see what 1.5 does for me.

    But I have seen Java run slow before, and I will tell you this: in every instance it is due to someone writing some needlessly complicated J2EE application with layer upon bloaty layer of indirection. All the wishing in the world won't make one of those behemoths run fast, but it's not fair to blame Java. Maybe blame Sun for EJB's and their best practices, or blame BEA for selling such a pig.

    Stuff I like in the Java world:

    • sun's 1.4.2 on hyperthreaded xeons
    • Jetty (fast!)
    • Piccolo XML parser (fast!)
    • Lea's concurrency library
    • Grosso's expirable cache [click]
    • hibernate
    • JAM on Maven [click]
    • eclipse
    1. Re:java *can* be fast... by Fnkmaster · · Score: 2, Informative
      Yes, EJBs are generally layers of needless cruft. There are lots of perfectly good situations that require distributed systems, and EJBs provide one of the worst models to solve truly partitionable problems and effectively distribute load, and if you just want reliability or failover capabilities, there are plenty of easier ways to get that than using EJBs.


      I agree with you - the only business apps I've seen that really NEEDED C++ were some very tight-loop mathematically intensive things where the 2x-4x performance difference imposed by lots of array bounds-checking became a limiter to performance optimization with the Java VM implementation - and that was easily solved by a small chunk of JNI code implementing the iteration over the arrays.

  41. Re:Caught up with the speed, but still the ugliest by I_Love_Pocky! · · Score: 4, Insightful

    All you programmers that say you can do anything in Java/C#/etc are terrible.

    Actually you can do most anything in those languages. Although for performance, and desgin reasons you may wish to use something else depending on the application.

    You have no respect for code. Learn assembly and then we'll talk.

    I know assembly, and fun as it is, it isn't well suited for high level projects where code reuse and mantainability are important. By the way, I have no respect for someone who knows assembly and thinks it is difficult. It isn't. And it certainly isn't graceful or elegant, but I love it all the same.

  42. Re:every year this happens... by Sebastopol · · Score: 2, Funny

    "It's always been written in Java."

    Except for the first Java compiler. ;P

    --
    https://www.accountkiller.com/removal-requested
  43. Re:Caught up with the speed, but still the ugliest by Inf0phreak · · Score: 4, Informative
    Would you please turn off the moronic "smart quotes" feature in IE?
    Seeing things like this:
    I&#146;m
    is hurting my eyes.

    This page has more information about this horrible malfeature.

    --
    ________
    Entranced by anime since late summer 2001 and loving it ^_^
  44. Slow C++ compiler by siesta+at+uni · · Score: 4, Informative

    The article says he used GCC to compile the C++ versions, but GCC produces code that isn't nearly as good as the Intel compiler for example. (Here, but no good if you don't subscribe)
    A lot of the test results are close, and I think a different compiler would change the outcome.

  45. Re:every year this happens... by Erwos · · Score: 4, Insightful

    I believe that Sun's javac bootstraps itself just like gcc does. That would be your java compiler written in Java.

    _Jikes_, OTOH, is written in C++. But that's not really the official Java compiler by a long shot.

    Your second requirement is absolutely bizarre. Does this mean you're not taking languages like Lisp, Prolog, Python, and Perl seriously, too? Those are all very nice languages for doing stuff in, but I'm pretty sure id never wrote a 3D engine in them. In fact, I was under the impression that id has never written a 3D engine in C++, either. Should we not take C++ seriously?

    IMHO: The measure of a language is not how easy it is to write an arbitrary application in it. It's how easy it is to write something for which the language was designed to do.

    -Erwos

    --
    Plausible conjecture should not be misrepresented as proof positive.
  46. Re:Caught up with the speed, but still the ugliest by DeckerEgo · · Score: 2, Informative

    Also check out SkinLF from L2FProd - it's a library that makes it very easy to use GTK themes, KDE themes or even both together to make a very nice native-looking interface. I use it with ConsultComm and have had very nice results.

  47. Can I have an infinite budget to write the code? by IvyMike · · Score: 4, Interesting

    Here is my experience with C++ vs. Java: At my company, we had a specialized image viewing program. The original program was written in C++ years ago, and performance sucked even on modern machines. It probably had a dozen man-years of time in it. We decided to re-write it in java.

    We knew java in theory should be worse than C++ at manipulating large blocks of raw data, so we spent some time architecting, prototyping, and profiling java. We quickly learned the limitations and strengths.

    The result? After 4 engineers worked for 6 months, we had a program that was rock solid, had more features, had a modern UI, and was WAY faster. Night and day; the old program felt like a hog, and the new program was zippy as anything. And the new code is fewer lines, and (in our opinion) way more maintainable. Since the original release, we've added severeal new features after day or two of work; the same features never would have happened on the old version, because they would have been too risky.

    So the question is this? Could we have re-written or refactored the C++ program and gotten the same speed benefits? No doubt, such a thing is possible. But we are all convinced there is NO WAY we could have done it with as little effort. The C++ version would have taken longer to write and debug.

  48. Now you're talking Profiling by GillBates0 · · Score: 4, Interesting
    and that's a topic that gets me all worked up (my Master's Thesis touch on Program Profiling).

    So, if the JIT computes Hot/Cold Paths, and optimizes the Hot paths, then it should work better and better on successive runs (as more and more profiling information is gathered). On the other hand, there will be cases where it performs worse, as profiles are gathered for specific inputs.

    That means that if an average of say 5 runs (on the same input) is taken, it will have an unfair advantage (since gcc did NOT have the advantage of profiling information (see man gprof or similar)). Using Profiling as an optimization tool is *always* unfair unless both tools are provided with the advantage of the same profiling information. This is a valid question for the author then: if the JIT/javac/JVM uses profiling information, gcc should too, for fair comparison.

    PS: I have seen this argument being made by my Professor and audiences at compiler conferences.

    --
    An Indian-American Hindu committed to non-violent thought/speech/action alarmed by the global explosion of radical Islam
  49. c# is FASTER than JAVA by gamesmash · · Score: 2, Informative

    Because c# is faster than Java, and Java is faster than c++, then by transitivity, C# is faster than c++. To back up my claim that c# is indeed faster, I cite as my source a researcher at cornell: http://www.cs.cornell.edu/vogels/weblog/2002/11/24 .html

  50. The language does matter by 3770 · · Score: 4, Insightful

    A few examples

    1) Java has bounds checking for arrays, C++ doesn't. This is specified in the language. This affects performance.
    2) Java has garbage collection, C++ doesn't. This is specified in the language. This affects performance.

    Also, the specification of Java says that it should be compiled to byte code and executed in a JVM.

    So the "language" certainly affects performance.

    --
    The Internet is full. Go Away!!!
    1. Re:The language does matter by bpellin · · Score: 2, Insightful
      Certainly the language affects implementation. However, the only relevant speed comparisons are between implementations of a language. Saying that language requirements/features will have an effect on performance is misleading.

      For example, good JIT compilers for Java are able to eliminate many bounds checks for arrays. Consider something like:
      for (int i = 0; i < 10; i++) {
      A[i] = ...
      }
      If the array A is of size >= 10, the compiler can easily prove the checks unnecessary, and the generated code will not contain bounds checks.
    2. Re:The language does matter by TRACK-YOUR-POSITION · · Score: 2, Insightful
      A third one I think is really important

      3) All Java classes are the equivalent of C++ virtual classes. There's a whole lot of dynamic type-checking, virtual function table lookups, and so forth when dealing with any Java objects, right?

      Which is what is striking to me about these benchmarks--there's all kinds of sorts and matrices and pure number crunching stuff, but I didn't see anything in which garbage collection or object management delays would start to become apparent. If what the other poster says about avoiding bounds checking is correct, that means that these benchmarks managed to avoid the major potential liabilities of Java performance.

      That's not to undermine the significance of these benchmarks--it's still very interesting that Java can approach and perhaps surpass C++ performance in any case with JIT.

    3. Re:The language does matter by gregor_b_dramkin · · Score: 2, Informative

      I believe you can declare a java method or class as "final". This optional behaviour is like C++'s default behaviour.

      BTW. I looked at the "shootout" article when it first reared its ugly head. I recall the Python code looking like it had been written by someone who had read 3 chapters of "Teach Yourself * in 21 Days". Utter crap.

      --
      You can never equivocate too much.
  51. Re:Caught up with the speed, but still the ugliest by FedeTXF · · Score: 3, Insightful

    I can say after using SWT in the Pocket PC platform that it sucks. The widgets are primitive, lack any real model implementation, they brake compatibility between minor versions, the most advanced things are done in the Eclipse UI packages not in the widget toolkit and the code you end up writting is ugly.

    Elaboration:
    No model: with swt you get the widget as a UI object with a field of type Object that you may or may not use as a reference to the object dislpayed. You ahve to write the code that updates th view when the underlying object changes and hende there is not real MVC pattern there. You can do it yourself. Imagine the huge pile of repeated effort in many projects around the world.

    Primitive widgets: the table widget is just a string grid. No masked text input, and it goes on and on.

    Ugly code: they use public fields for setting state to widgets not constructors or factory methods or even setters. They have integer constants for decribing widgets and you have to use those and see them. Creating a label requires using new Label(SWT.LABEL) and creating a horizontal Line is new Label(SWT.LABEL | SWT.HORIZONTAL). So much for hiding complexity.
    There are 4 type of layout managers, the initialization is verbose and in fact only 1 are relevant, GridLayout, the other 3 are special cases of the former.

    The more advanced widgets are not in SWT, only in the Eclipse centered custom libraried. The SWT mantainers say those classes are for use in the eclipse UI and they don't mean thme to be general purpose, use thej if they fit, but don't ask for improvements.

    The only way SWT is justified is when you have very low resources (a pocket pc) or need to compile with gjc. Otherwise, Swing is way better even when it is far from pefect.

  52. Re:Nort really surprising by IMarvinTPA · · Score: 2, Informative

    I think you have some fatal flaws in your C code. Your string buffer isn't long enough to hold what you are doing. And they aren't doing the same thing. The first code is going to count to 10240. The second code is going to display ascii characters from null through to character 255 and then do some very bad things.

    Bad code, BAD!

    IMarv

  53. Re:Benchmarks by Hoodsen · · Score: 3, Interesting

    From comments Doug Bagley made about the "Shootout" (where the benchmarks came from), no, I don't think it is an accurate comparison, or at least a conclusive comparison between C++ and Java. His comments from his conclusion:

    I put it on the web because I thought it would interest others. Even though I put disclaimers on the page, and I try not to make any claims, I see some people say the shootout shows that "language X is faster than language Y".

    That claim is probably premature and hence, bogus. I suppose you could make the claim that, in "Doug's word frequency test, on a PII-450 running Linux 2.4, given a certain input, language X is faster than language Y" Assuming, of course, that I haven't made any mistakes. Some of my tests are also arguably poorly designed and meaningless. (Hey, if you have some better ideas, please write to me).

    Benchmarks are notoriously misleading, and perhaps mine aren't any better, although I do try. Benchmarks tell you about results in a very specific case. Drawing a general conclusion is problematic.

  54. O3? Equivalent programs? by morcheeba · · Score: 4, Insightful

    Why did he use only -O2?

    -O3 adds function inlining and register renaming.

    Also, some of the code doesn't look too much of a test of the language, but more of a test of the libraries. Both versions of hash rely on the library implementations, and it looks like hash.cpp does an extra strdup that the java version doesn't. I don't know either of the hash libraries well enough, but I don't see why this significant slowdown would be necessary in the gcc version.

  55. Re:Sorry, no. by Knight2K · · Score: 3, Interesting

    One X-factor is JVM warm up. When benchmarking Java you should run the test multiple times in the same VM. This gives you a better real-world feel of what a Java app will do during continuous use, at least from a server perspective.

    Desktop app use cases may be different, in which case your test may be valid. Start-up time is definitely a significant part of the user experience. At one point Java 1.5 was supposed to have shared VMs, so that Java can start at system load time. Other VMs would just then be a matter of forking another process off the already running VM, thus increasing startup time. My understanding is this has fallen off the truck for that release, but people are working on it.

    --
    ======
    In X-Windows the client serves YOU!
  56. Troll by stratjakt · · Score: 5, Insightful
    This test proves that Sun's optimized Java compiler and VM are faster on Red Hat than gcc.

    Gcc is designed for compatibility with a wide range of architectures, and is not optimized for a single one. He also (apparantly) used stock glibc from Red Hat. And only one "test", the method call test, showed java to be a real winner. And even then, it's server-side Java, which is meaning less when you talk about it as a day-to-day dev language (ie; creating standalone client-side apps).

    Intel's (heavily optimized) C++ compiler should be a damn sight faster, and so should VC++.

    This "comparison" is so limited in scope and meaning, that this writeup should be considered a troll.

    Hell, read his lead-in:

    "I was sick of hearing people say Java was slow, when I know it's pretty fast, so I took the benchmark code for C++ and Java from the now outdated Great Computer Language Shootout and ran the tests myself."


    Ie; I set out to prove Java is teh awesome and c++ is teh suck!

    If anything it proves something I've known intuitively for a long time. gcc does not produce x86 code that's as fast as it could be. That's a trade-off for it being able to compile for every friggin cpu under the sun.

    I can't wait till RMS takes personal offense and goes on the attack.
    --
    I don't need no instructions to know how to rock!!!!
    1. Re:Troll by Ninja+Programmer · · Score: 2, Informative

      Gcc is designed for compatibility with a wide range of architectures, and is not optimized for a single one. He also (apparantly) used stock glibc from Red Hat. And only one "test", the method call test, showed java to be a real winner. And even then, it's server-side Java, which is meaning less when you talk about it as a day-to-day dev language (ie; creating standalone client-side apps).

      Intel's (heavily optimized) C++ compiler should be a damn sight faster, and so should VC++.


      This is a slight misrepresentation. gcc actually does quite respectably on x86 platforms -- its easily as good as MSVC++, and its clear that the gcc people have put a lot of work into this compiler. Of course, the Intel C++ compiler is truly awesome and leaves pretty much every other x86 compiler in the dust, but this is really a case of Intel just putting a truly amazing effort into their compiler rather than anyone else comming up short.

      The real issue with these tests is that pretty much none of them have real computational inner loops. They all measure unlikely program overhead that could easily be removed with any reasonable rerendering of the code.

    2. Re:Troll by KZigurs · · Score: 2, Insightful
      " And even then, it's server-side Java, which is meaning less when you talk about it as a day-to-day dev language (ie; creating standalone client-side apps)."

      As far as I understand ONLY field where Java can be used succesfully now IS THE server side. And believe me - there is way more ordinary programmers that happily crunch their daily duties creating xml/xsl/html/xhtml/whatever spitting JSP's or servlets than hardcore C++ GUI developers.

      Of course this will probably change once Java will get something decent for graphics, maybe even Qt in native Java... Existing graphical layers are simply sickening to work with.

      But for everything else - there is a nice, decently fast (and believe me - you DO NOT need those 16xCPU power5 grids or that 8.244012% difference in execution speed - when developing you always should be looking for simplest/easiest and most practical solution. At least in the main cases. It MAY be different if you are one of CuBase developers.).

  57. Magicosm by wurp · · Score: 2, Informative
    Magicosm is a 3D real time persistent online world. It's not released yet, but we have about a dozen beta testers. If we were funded, we would be way done by now; working on things only in your spare time is a bitch ;-)

    We use Xith3D (primary written by our main client developer), a Java3D workalike. Xith3D was spun off in response to Sun's news that Java3D would no longer be supported. Sun's decision may have been reversed; I'm not entirely sure.

    Anyway, we have slick looking 3D that performs just fine; comparably to other engines. It's on top of an API (Xith3D/Java3D) that sits on top of opengl.

    There have been several good 3D java games displayed at the GDCs, stuff from FullSail and GetAmped.

    By the way, the project is currently going through a lull as I work on another side project (an online yard sale) and the primary client developer has had to leave the team to spend more time with his family. Send us a note at jobs@magicosm.net if you want to help out as a developer, 3D artist, system administrator, or (especially) investor!

  58. Java is not faster than optimized c++ by cardshark2001 · · Score: 3, Insightful
    It's just not possible. It could be comparable, in limited cases, but not faster. It just can't be. If you find that it is, there's something wrong with your experiment. Does this mean Java is bad? Not necessarily. It depends on your purpose.

    Okay, so how could I make a blanket statement like that? In this case, the author of the paper merely used a compiler switch in gcc (-o2). That doesn't mean his c++ was highly optimized. It just means he told the compiler to do its best. If you really wanted to highly optimize c++, you would study the compiler and how it works, and you would profile the actual assembly that the compiler generates to make sure that it didn't do anything unexpected. Given *any* algorithm, I can come up with a c++ implementation that is faster than a Java implementation. Period.

    The java compiler actually compiles to a virtual opcode format, which is then interpreted by the java virtual machine at runtime. Imagine if you needed to talk to someone on the phone, but instead of talking to them, you had to talk through an intermediary. Is there any possible way that it could be faster than talking to the person directly?

    Now, I'll be the first to point out that a badly implemented c++ algorithm could be much slower than a well implemented Java algorithm, but I'll take the pepsi challenge with well written code any time, and win.

    Relying on benchmarks and code somebody else wrote doesn't prove anything. Did he get down and dirty with the compiler and look at the generated assembly code? No, he did not.

    Move along, there's nothing to see here.

    --
    WWJD? JWRTFA!
    1. Re:Java is not faster than optimized c++ by iapetus · · Score: 2, Insightful

      If that's the approach you're going to take, though, then you might as well just code in assembly - cut out the middle man. Benchmarks like this are entirely worthless - the main thing they do is stir up the rabid language zealots out there, 5% of whom will be crying from the rooftops that it's all a lie and C++ is better, 2% of whom will be insisting that the results cast Java in a bad light and that it should be seventeen times faster than C++, the other 93% will be pimping their own language of choice.

      At the end of the day, the real question that I should be asking myself is which language gives me the best balance of maintainability, ease of development and elegance of expression. I don't care if you can shave two instructions from your generated assembly code at the cost of making your code ugly as hell and impossible to maintain. This is a bad trade-off that only matters to the most anal of benchmarkers and those rare few who really do need the absolute maximum performance from a (typically small) segment of their code. I want to know which language is going to make me most productive, and there's no objective measure of that which I trust as far as I can throw it.

      --
      ++ Say to Elrond "Hello.".
      Elrond says "No.". Elrond gives you some lunch.
    2. Re:Java is not faster than optimized c++ by p3d0 · · Score: 2, Informative
      Runtime optimization analyzes the bytecode that's running and can come up with ways of optimizing things at runtime. However, this optimization was coded into the JVM, and there's absolutely nothing that stops you from emulating that approach in C.
      Wrong. JIT compilation offers you two things you can't get from a static compiler: (1) dynamic information about a particular run of the program, and (2) the opportunity to make optimistic assumptions, knowing you can re-compile if your assumptions are violated.

      Suppose that during a particular run, there is a particular variable x that, whenever we look at it, always has the value 42. Now we want to compile a method that uses that value. A JIT can optimistically assume that value will always be 42. Now it can go to town on optimizations involving that variable. Got an "if(x > 10)" statement? You can omit the compare and branch. Got a division with x as the denominator? You can omit the divide-by-zero check, and turn the divide into a cheaper multiply-by-reciprocal. And so on, and so on. Then, you register your assumptions with a runtime service that is capable of re-compiling the method of your assumptions turn out to be incorrect. If you ever see that variable with a value other than 42, you recompile it (and do some fancy footwork to deal with threads that might already be running the obsolete version).

      What you end up with is a method implementation that a static compiler just could not produce. Perhaps, if it were very smart, it could use profile-directed feedback to create a specialized version of the method for each of a number of "likely" values of x. However, unless you want to try to cover all 4 billion possible integer values, you must include a backup version for when you turn out to be wrong. Plus, you'll always have the overhead of choosing which of the specialized versions to call in the first place. This is all overhead the dynamic version doesn't have.

      So it is definitely not impossible for a dynamic compiler to outperform a static one. It is just very rare, given the current state of the art of compilers.

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  59. Re:Largest Prime by jfengel · · Score: 2, Informative

    I know you're joking to make a point, but you do realize that 1 isn't prime, right? That's not just a matter of arbitrary definitions; a lot of theorems that apply to primes don't apply to 1.

  60. SWT by Master+Of+Ninja · · Score: 2, Insightful

    But until it is bundled by default with the JVM and JDKs, it will still be hassle to get SWT working for normal users. If Sun replaced the swing toolkit with SwingWT and linked it to SWT, I would think there would be a great improvement in performance of most Java GUI apps (and most of them really do suck - the only good one I have seen is MoneyDance).

  61. Re:Caught up with the speed, but still the ugliest by deputydink · · Score: 2, Interesting
    I couldn't agree more. I have been making a serious effort in the last few years to open my mind to technologies (like Swing) i had quickly dismissed earlier on.


    Apple's swing implementation is pretty fast, good looking, usable and well (but not *fully*, you have to implement your own Apple-W handlers and such, which is i guess to be expect) integrated with the host OS.


    Additionally, the support for JNLP/WebStart is very satifictory on both XP and OSX. A fine java deployment techonology that I believe is underrated.

  62. The performance hit is negligible... by bl8n8r · · Score: 2, Interesting

    Depending on the application. I will gladly trade the write-once-run-almost-anywhere advantage for a little heavier application, within reason. (Sun's "soundtool" java app is a sadistic waste of reason) Not having to support multiple platforms, compilers, Licenses, IDEs, utility applications, etc, etc is a big plus too. Java's inbred sluggishness is not cause to ignore the advantages it offeres in other areas. I also like the idea of having some competition in the commercial development arena again.

    --
    boycott slashdot February 10th - 17th check out: altSlashdot.org
  63. Re:Caught up with the speed, but still the ugliest by kaffiene · · Score: 3, Funny

    For years it was "Java is too slow" Now it's too ugly??

    Sheesh.

    I'm sure one of Swing (with it's several different look and feels and skinnable interface) or SWT or AWT will fit the bill.

  64. Re:This doesn't make any sense... by MetalShard · · Score: 2, Interesting

    If you are going to do that just make it run through and compile the entire thing in one shot rather than doing it a small bit a time. Then the end user won't have to experience the "just in time" part of the compile. I don't understand why if you can "just in time" compile it, you can't just compile it at build time and get it over with.

  65. different requirements by vlad_petric · · Score: 4, Informative
    The server one is optimized for throughput and concurrency, whereas the client one for latency.

    You might think that the two are the same, but the two settings actually make a visible impact if you're running on a multi-processor system. Most notably, the garbage collector and locking primitives are implemented differently.

    --

    The Raven

  66. Quake2, Alien Flux, Tribal Trouble by maxgilead · · Score: 2, Informative

    Sure, there's java port of Quake 2, there's Alien Flux, Tribal Trouble. But, as others already mentioned Java is mostly used for programming game logic. It's performance is constantly improving and only recently it gained enough speed to be seriously considered for writing entire game engines.

  67. Bull hockey by wurp · · Score: 2, Insightful

    If one program uses profiling information to run faster than another, it runs faster nonetheless. I agree with other posters that this is comparing compilation & runtime environments rather than languages, but when I care about how fast a program runs I care about how fast it runs, not how fast it would run in some hypothetical nonexistent environment. C++ would probably be faster if it had some kind of JIT environment to run in, but it doesn't, and as a developer trying to write fast software, that's what I care about.

    That said, I doubt the performance differences are enough to affect my decision about what language to use, unless I am writing some application that does enough computation that a person has to wait on the program, rather than the other way 'round.

  68. The methodology used here sucks by Troy+Baer · · Score: 3, Interesting
    The author doesn't really explain why he didn't compile with -O3 aside from a very slight amount of hand-waving about space-speed tradeoffs, which quite frankly I don't buy. If you're benchmarking, why wouldn't you optimize as heavily as possible? If he was really interested in benchmarking this stuff objectively, he could've at least shown that there wasn't much different between -O2 and -O3. Not to mention the question of whether g++ generates good binary code on a given platform...

    This didn't exactly fill me with optimism either:

    I don't have an automated means of building and benchmarking these things (and the scripts that came with the original shootout didn't run for me). I really do want you to test it on your own machine, but it's going to take some work, I guess.
    This would seem to imply that the author does not know much about either shell scripting or Makefiles. I'm not sure I'm willing to trust benchmarks from somebody who can't figure out an automated way to build and run them.

    --Troy
    --
    "My life's work has been to prompt others... and be forgotten." --Cyrano de Bergerac
  69. Re:Sorry, no. by maraist · · Score: 3, Interesting

    I'm inclined to agree with you, except that the benchmarks were qualified as talking about being relevant to enterprise applications. In such a situation, run-time optimizations are critical.

    While it is entirely possible [in c/c++] to use a profiler to generate compiler hints so as to generate even more efficient code, this is rarely performed, and often is not free. A VM otoh does get this capability for free.

    Additionally, the java memory manager has a slight edge over tradditional malloc's for total throughput (though the best throughput configurations have horrible spuradic response times). It is also possible to choose a different memory manager for c/c++, but this too is rarely used.. Moreover, it is much harder to have 3'rd party code integrate well with a garbage-collector model. Java enforces garbage collection, and thus optionally gets the particular performance gains (being free to trade off throughput for responsiveness no matter what 3'rd part code is integrated).

    As was pointed out, one of the strenghts of C/C++ are pass-by-value, which allows memory allocations to be avoided all-together, but at the cost of copy-time and robustness of code. If a method call requires instantiation, c/c++ have the option of passing in a local [stack resident] structure to be populated by the method. However, this is fodder for buffer-overflow exploits, and notorious for otherwise bad code (accidently caching the address of a value that lives on the stack). Thus, given that c++ will use "new" and thus generally perform a malloc, the same performance issues above apply, and c/c++ may have the additional overhead of copy-by-value.

    The fact that you have to explicity declare a c++ parameter as pass-by-reference suggests that those interested in "good programming practices" (tm) will only make a pass-by-reference if you intend to modify it's contents. Thus "clean" code in c++ will be copy-intensive... For fairness, clean java code should always make immutable wrappers for any non-modifyable code, thus requiring an all together different liability (and thus I can't make any claims as to which would be faster; wrapper object instantiation or deep parameter-copy). Though all primatives are available in java as immutable objects (Strings, Dates, etc). Moreoever, clean OO-code should always use method getters, and make all fields private (not even protected). Both C++ and jit'd java can inline these getters.

    I haven't looked at the benchmark code, but the above are common components which make a big difference when scaling to large enterprise applications, or even when merely writing a glue application which integrates many large 3'rd party libraries. In c++ you don't have a lot of control over the 3'rd party libraries (in terms of their design trade-offs), but with a VM, you are largely sheltered and have many configurable alternatives.

    --
    -Michael
  70. Re:Sorry, no. by afidel · · Score: 3, Interesting

    No, it doesn't. Check out WordPerfect Java, Novell ConsoleOne, or any other large Java project for a real world counter example. Java applications are slow to load for any meaningfull piece of client side software. Java works wonderfully for middleware applications but is simply the wrong tool for client side software. When I can reboot the computer and load MCC faster than I can start ConsolOne there is something seriously amiss (and no jokes about having to reboot, I have windows PC's with 200 day uptimes limited only by patching sessions, which is true for any properly maintained OS).

    --
    There are 4 boxes to use in the defense of liberty: soap, ballot, jury, ammo. Use in that order. Starting now.
  71. Re:Caught up with the speed, but still the ugliest by Anonymous Coward · · Score: 2, Insightful

    > By the sounds of it you have no idea what a good GUI is. Skins and themes do not a pretty UI make.

    Since Swing has all the GUI elements of every other toolkit, what would make a pretty UI if not skins/themes? A bad design can be done in any toolkit if the designer doesn't have a good sense of layout, etc.

  72. java methcall benchmark not making virtual calls by bgs4 · · Score: 2, Insightful
    Notice that the C++ methcall code declares "activate" a virtual function, but not so in the java version. No kidding you're going to get better performance.

    Presumably the java compiler inlined the function call. Do the math-- 4e9 function calls in 2.5 seconds. That's 1.6e9 function calls per second. On a 3.0 GhZ machine that's two cycles per call, so they're probably all inlined.

  73. it's reasonable by trance9 · · Score: 2, Insightful

    In response to what many of you have and will write:

    -- there is not necessarily any "extra layer" created by the JVM. the whole idea is that the JVM is actually a run-time compiler, and when it's done compiling the .class to native code you really have native code directly executing.

    -- the JVM runtime compiler can perform optimizations that are not available to a C++ compiler. for example, if the JVM realizes that there is only one instance loaded of an abstract/virtual class it can compile all the code that accesses it statically against that single code, as if there were no inheritence at all, saving a pointer reference. a C++ compiler can never do that because it does not know what you will link against.

    -- Many of you are simply going to find ways to criticize Java because you are religious. You used to criticize performance, and if that is taken away from you, you will say it was never really important and criticize something else. You need to think whether or not you are being objective and rational, or simply theocratic.

    -- Yes you could likely optimize the C++ code better. Some suggested replacing the inefficient cout's with printf's but that is really eliminating the ++ part of the C++ language. If you can't take advantage of C++'s OO features then there isn't any point in comparing the language with Java--without those higher level features you are programming in the 70's. Guess what, assembler is even faster. So it is fair to compare C++'s high level features with Java.

    -- Repeat: Some of you are simply religious.

    1. Re:it's reasonable by cardshark2001 · · Score: 2, Insightful
      What you're basically saying is if I want to hand optimize every line of code I write, rather than concentrating on the task at hand, then I should use C++, but if I want the compiler to do the heavy lifting then I should use Java?

      No, I'm not saying that at all. I'm saying Java can be faster, in some circumstances, if you are talking about a naive implementation. I never said that Java would always be faster, and I hardly think that is the case (some undergrad troll who made the front page of /. notwithstanding).

      However, when you need the utmost in performance, and second best won't cut it (and assembly is too much hassle), c++ is your best choice. Do you think Doom 3 could possibly be written in java? I'll answer that one for you - no way in hell. To suggest otherwise is ignorant and ludicrous at best, trolling at worst.

      --
      WWJD? JWRTFA!
  74. I Smell funny? by Bill,+Shooter+of+Bul · · Score: 2, Funny

    Well, you'd better tell your mom to switch perfumes.

    --
    Well.. maybe. Or Maybe not. But Definitely not sort of.
  75. Java -server always breaks micro-benchmarks by giliath · · Score: 2, Insightful

    The -server mode of java causes the JVM to recompile code for the most used code path. I have not looked at the exact code for each of the tests, but in many cases this can result in the JVM optimizing out the code completely. You have to be extremely careful when doing benchmarking of languages like java because the JVM is able to dynamically recompile the code to remove the actual work, if the results of that work are never used.

    ~Giliath

  76. Re:Can I have an infinite budget to write the code by kaffiene · · Score: 2, Interesting

    I have two decades worth of programming experience, using most of the languages out there.

    I'm currently coding in C# (which sucks arse) and Java for object tracking in video. The Java code rocks - it's simple to write, it works and it's really fast. Video processing uses lots of loops with runtime constants which the hotspot JVMs seem to generate extremely fast code for.

  77. You are eliminated the whole point of profiling. by SuperKendall · · Score: 2, Interesting

    Why is it "unfair" that Java is actually able to profile what is being run, vs. a static compiler having to guess? That is a very real advanatage of Java and should not be "leveled out" of the test. The benefit given by that technique is exactly what I would like to see.

    --
    "There is more worth loving than we have strength to love." - Brian Jay Stanley
  78. On the flip side by msgmonkey · · Score: 4, Insightful

    When C/C++ uses profiling it will only ever produce one "best case" compilation for a given function.

    With any JIT system you have the opertunity to use the profiling information from a given "window" of the execution so there is the possibility of having more than one compilation for a function.

    Now, I do not know how sophisticated JAVA JIT compilers have become but this is one area where JIT will have an upper hand over a static compiler.

    OTOH, these tests do not look like there is enough significant variation in the execution path for profiling to make a large difference.

  79. One more... by Rufus88 · · Score: 5, Funny


    anything else?

    Yeah, Kuro5hin is better than Slashdot.

  80. Re:This doesn't make any sense... by swillden · · Score: 2, Interesting

    I don't understand why if you can "just in time" compile it, you can't just compile it at build time and get it over with.

    You can, of course, and there are Java compilers that do (e.g. gcj). What this benchmark really demonstrates is that doing it may be suboptimal. Sun's JVM does something more than "just in time" compilation, it also does interpretation and profiling. The first few times a bit of code gets executed, the JVM will not just-in-time compile it, preferring instead to interpret the bytecodes and gather some statistics.

    After the same pathway has executed enough, the JVM will decide that it is a "hot spot" that will benefit from compilation to machine code. This compilation, however, will be performed with the benefit of the runtime statistics that were gathered while interpreting the code. Assuming that future executions will have characteristics similar to past executions (generally a reasonable assumption), the JVM will create machine code for what it knows is the typical execution profile.

    This profiling and late optimization is where Java gets the chance to beat pre-compiled code, after it's warmed up, anyway.

    Very good programmers who know their compilers and processors can do the same thing with compiled languages like C and C++. In fact, they can do a far better job because they have a better understanding of what the program does. However, that sort of optimization is hard work, error-prone, not very portable and interferes with maintainability.

    The JVM doesn't optimize as well as a good programmer, but it's a whole lot cheaper.

    --
    Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
  81. My Hero! by 3770 · · Score: 4, Insightful

    No, I'm not being ironic.

    I'm tired of some programmers expecting to be worshipped because they know assembly.

    Assembly isn't all that.

    For some uses, it is the right tool. For 99.9%+ it most definitely isn't.

    --
    The Internet is full. Go Away!!!
    1. Re:My Hero! by 3770 · · Score: 2, Insightful

      I know assembly and I have studied CPU designs. I also know compiler technology and I have written a compiler (commercially).

      I abide by the rule "to write simple code and only optimize when needed" and it has worked great for me.

      I'm not crapping on those that know assembly, only those who think that it gives them a right to look down on those that don't.

      I stand by my rant.

      --
      The Internet is full. Go Away!!!
    2. Re:My Hero! by kfhickel · · Score: 2, Funny

      That's right, assembly isn't all that!

      learn microcode, then come and talk to me!!!!

      (yeah, I'm old, so what!) ;>

    3. Re:My Hero! by Kosgrove · · Score: 2, Informative

      One of the most important reasons software has advanced is exactly BEACUSE of information abstraction - API's, object-oriented computing.

      In my experience, it's not a bad thing to be beholden to an API author. The author(s) likely know the system better than you. It's one of the things that helped humanity advance in general - specialization. It shouldn't be taken to the extreme, of course, SOMEONE has to know how the stuff works, but not most programmers.

      Assembly language is good to know, but many (most?) coders will not ever have a need to touch it, unless they are doing embedded design or compiler development. There are much more useful things to learn for those of us that write software. For example, I am absolutely shocked at the number of students who graduated with me that had taken a SPARC assembly class (required), but knew zero about relational databases. (Although to be fair to my alma mater, Penn State, I believe that situation has since been rectified.)

      By the way, I know assembly. MC68k as an undergraduate, a year of MIPS architecture as a graduate.

  82. Meaningless Question by Waffle+Iron · · Score: 2, Insightful
    There is no one answer to the question "which language is faster?". It all depends on that the workload is.

    For example, Java with its JIT can easily match a C compiler on bit-banging and number crunching small data sets when there's no memory allocation going on. However, that isn't what most people are waiting for when they run typical interactive applications.

    If a system is not I/O bound, most applications tend to be doing a lot of string manipulation or similar operations on small objects. When Java operates on strings, it tends to create, discard and garbage-collect a large number of short-lived string objects because Java's strings are immutable. This consumes quite a bit of CPU and memory.

    Some C++ applications are written the same way. Many KDE applications are rather sluggish, probably because they are taking advantage of a lot of automatic management of a lot of QT objects. STL-based C++ apps can also be sluggish if you use high-level containers like tree maps without a keen awareness about what kinds of extra copying and thrashing can happen under the hood when you use them. Even in C, if you use high-level libraries, you can get sluggish performance, as some of the more bloated Gnome apps demonstrate.

    However, C++ programs, even STL-based ones, may also be written in a different style that takes advantage of mutable strings and handles object allocation manually. This tends to reuse data structures in place, eliminating memory management overhead, and it has the very important effect of keeping caches and page tables much more localized. This is more bug-prone than the alternative, but can provide a substantial performance improvement that Java can't hope to touch on a similar dataset. The drawback is that the app is much more likely to crash unless it was written by a top-notch developer; in fact, this kind of programming is the cause of many of the security problems plaguing the various OSes over the years.

    (People often point out that nobody writes kernels in Java. That's because they tend to be written using the manual memory management style with as many static data structures as possible to squeeze out more performance. People don't use popular high-level C++ libraries to write kernels for the same reasons.)

    Bottom line, the answer to which language is faster will always be "it depends". It depends on what the program is doing, and it depends on how the program was written. A couple of datapoints from a language shootout don't help to resolve the issues.

  83. Re:Can I have an infinite budget to write the code by swillden · · Score: 3, Insightful

    Unix GUIs are far easier to implement with Java than with C++. Athena/Xlib are a huge fargin' hassle and no-one ever gets the widgets right. Motif is too expensive to license.

    You really need to look into Qt. It's much easier to use than Swing.

    --
    Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
  84. Re:Caught up with the speed, but still the ugliest by braindead · · Score: 2, Interesting
    • P.S: yes i have seen beautiful swing apps, yet they look out of place.
    I guess it's a matter of taste. You may prefer that your java app looks the same as the other apps around it at the time, but I prefer my java app to look the same on my windows machine and on my linux machine.
  85. Java is not under one vendor!!!! by SuperKendall · · Score: 4, Insightful

    You are once again spouting the tired old line that Sun is the master of Java. Not at all true, Java's fate is controlled by a whole host of companies - including IBM. Take a look at the reality of Java platform evolution at the Java Community Process web site.

    It's a standards body just like any other, just more open.

    P.S. - Aside from that gripe being wrong, I agree with the other poster that you should look into Objective-C to address other issues. Look for "GnuSTEP" for cross-platform objective C GUI work. It's just nicer to use on a Mac as they have very good tools (though in fairness I have never looked at what GnuSTEP tools might be around, I just can't imagine them being quite as good as the tools Apple has sunk so much effort into!).

    --
    "There is more worth loving than we have strength to love." - Brian Jay Stanley
  86. Agree, Java can be great with a little profiling by SuperKendall · · Score: 2, Insightful

    I had similar experiences writing a Swing app around six years ago (just around the release of 1.2). At first the Swing app was a little slow, but after a number of rounds of profiling and tuning it was really, really fast - with an MDI interfance and a lot of heavily customized controls on very busy forms. The app worked great even on slower computers, and was well received by the client.

    There is no reason Java has to be slow. It's just prone to having a lot of layers stuck on things when they might not need to be. As you say, for a lot of work people are doing J2EE stuff may well be overkill (though even that can work with simialr efforts to tune).

    Basically, with any VM app tuning is key. As C# people are only just now starting to realize... a shame the tools there are a lot more primitive that what Java has to offer.

    --
    "There is more worth loving than we have strength to love." - Brian Jay Stanley
  87. The main flaw of such benchmarks... by WARM3CH · · Score: 2, Interesting

    is not just using the right compiler and right options, but the bechmark codes they use. Just look at this bench mark, are they really C++ codes? Are they the type of the codes that pushes the programmer to use the most advanced techniques? I for one, use C++ because of Boost, because of Blitz++, because of not having a garbage collection mechanism. Why these benchmarks never use a code to calculate some really challenging processing like a series of operations on large matrixes of complex numbers? Why they don't try benchmark where you have to allocate and free a large number of nodes in a large scale graph traversal and coloring program? Why they don't try to see how ESPRESSO performs in C++ and Java? How about large scale FFTs? Raytracing? Finite elements? JPEG compression and decompression? You can get any results you wish in comparision of any two languages and implementations as long as you don't write even a single routine of real-world code.

  88. The speed of java is only one concern by adiposity · · Score: 3, Insightful

    What concerns me most is the amount of memory it requires. In theory, once the requisite stuff is loaded into memory, Java byte code can be processed at nearly the same rate that C++ code is. Depending on the bytecode and assembly that are generated in each case, Java or C++ could end up being faster. I think it's obvious that Java incurs some overhead in translating the bytecode, which ought to slow it down *some*, but that amount can be minimized.

    On the other hand, Java takes a great deal of memory. If C++ had a dedicated server sitting in memory, ready to execute commands for it, it probably would speed up execution, but that wouldn't mean C++ were faster.

    After accepting the memory hit for Java, the performance on things like apps servers seems to be pretty decent. I have yet to use a java client application, however, where I didn't feel that it was sluggish (even after loading). There are only two explanations: all java code is written poorly, or Java inherently causes a performance hit.

    As we abstract languages more and more, we see performance hits for increased functionality and ease of developing. We also see that, because of the easier development, it is easier to improve scalability and use more efficient algorithms. It is rare that a program cannot be sped up by hand-optimizing the assembly, but it is also rare that anyone has time to design the much more critical optimized algorithms at such a low level. Therefore, I predict that eventually Java (or something like it) will be embraced as programmer time matters more than speed of execution.

    The one thing that disturbs me about Java is that, while in C++, it is easy to change the assembly while maintaining the C/C++ code, in Java, you are tied to platform-independent code, which prevents you from doing platform specific optimizations. You have to depend on the native java implementations and/or widget toolkits for those kind of things. And so far, although the situation is improving, I've been pretty unhappy with the speed and my ability to improve it.

    -Dan

  89. Cross platform by Psymunn · · Score: 2, Insightful

    C++ is as cross platform as the libraries you use. The game code i'm writing so far (it's a simple game, doesn't have any assmebly or optimisation... just a keen like side scroller) compiles under both windows and linux. Using the same make file. How? I use SDL for everything. I've had equally pleasent experiences with Qt. Portability in C and C++ is all based on the libraries.
    Of course being able to compile on multiple platforms and being cross platform aren't the same thing but I still think that it is in the benefit of people producing software for Linux specifically, to write code that will port to Windows without to much avail (who the hell uses \?)

    --
    The Neo-Bohemian Techno-Socialist
  90. Re:Just one game by Mindcry · · Score: 2

    i did read the article, but i kinda think i'd need to see more than one source as well as hear comments about any flaws in the tests before accepting this as the new order.

  91. Quick analysis... by the_skywise · · Score: 2, Informative

    In the bulk of his results, C++ on an i686 beat out the CLIENT JVM every time except in two tests. Object creation and word count. In the object creation test the code is biased towards Java. He's creating the objects AND DELETING THEM in C++, but Java's garbage collection probably isn't doing the deletion at all.

    The other test is the word count. This one is interesting because he sets the streambuffer to 4k in both Java and C++. But in the C++ version the stream won't preload to fill the buffer. So the amount being cached is UNKNOWN. I can't speak for the Java version but I bet it preloads the entire file.

    That leaves the Server JVM switch. In which case I think you're seeing alot more code inlining then the standard C++ compiler generates.

    Either way, this is hardly a definitive test.

  92. Explanation by gillbates · · Score: 4, Interesting

    Reviewing the console log, we find that when java programs were tested with a large number of iterations, Java only performed better on one test.

    • We don't know which OS was used. While each C++ program must have been loaded entirely each time, the JVM may very well have remained cached in RAM between tests - hence a faster startup time, which explains:
    • Java is actually slower than C++, but because the JVM was already cached in RAM, it ran faster on those tests which involved a relatively small number of iterations. However, when the number of iterations was increased, Java was always slower than C++, with the exception method call and object instantiation:
    • Object instantiation isn't really relevant because of the fact that C++ programs call the OS for every single memory request, where as Java can pool it. This test measured the speed of the kernel's malloc more than the speed of C++.
    • In most of the C++ code, IO is placed in the inside loops, meaning that the program is really testing the throughput of libc and the OS, as opposed to the efficiency of the generated code.
    • An interesting note: the Java client won none of the benchmarks.

    I know that Java has many strengths, but speed isn't one of them. Looking at the results, we see the g++ runtimes are much more consistent than those of Java - on some tests, the Java Server is faster than the client by a factor of 20!? How could a programmer code without having any realistic expectation of the speed of his code. How embarrassed would you be to find that your "blazingly fast" app ran slower than molasses on the client machine, for reasons yet unknown?

    When it comes to speed, compiled languages will always run faster than interpreted ones, especially in real-world applications.

    But discussions of language speed are a moot point. What this really tested was the implementation, not the language. Speed is never a criteria upon which languages are judged - a "slow" language can always be brought up to speed with compiler optimizations (with a few exceptions). I suspect that if C++ was interpreted, and Java compiled, we'd see exactly the opposite results.

    In short, the value of a language consists not in how fast it runs, but in what it enables the programmer to do.

    --
    The society for a thought-free internet welcomes you.
    1. Re:Explanation by areve · · Score: 2, Informative

      java is JIT compiled not interpreted

    2. Re:Explanation by neurojab · · Score: 2, Informative

      >When it comes to speed, compiled languages will always run faster than interpreted ones, especially in real-world applications.

      It's a bit simplistic to call Java an "interpreted" language. A Java source file is compiled into bytecode. Modern JVMs then take this bytecode and use a Just In Time compiler to compile it into machine code just before it runs. Naturally this is a bit of overhead up front, but once the class is JITed, it will perform on the order of natively compiled code written in another language.

  93. Re:Riiiiiiight by l33t-gu3lph1t3 · · Score: 2, Informative

    Windows nowadays *is* very stable. I've been working as a systems administrator over Windows NT, 2000, XP, and 2003 Systems for about 2 years now (obviously I haven't spent that much time on 2003...) and you know what? Except for one really screwy problem that later turned out to be memory-related, I have never had stability problems with those flavours of MS Windows.

    Ok that's not entirely true. I've seen Windows stability problems. They were the result of user stupidity like truckloads of spyware and hard disks with no space left.

    And as far as "idiotic debug statements" go, GCC holds the frikkin crown for those. When java compiler or runtime crashes, it tells you more about what went wrong than C++ does...perhaps the reason you see amateurish java programs is that the amateurs and programming students are switching from C++ (a language no one should use unless they're supremely gifted as a programmer) to Java (a language that saves them from their own stupidity).

    --
    ------- "From bored to fanboy in 3.8 asian girls" ----------
  94. Re:Sorry, no. by phasm42 · · Score: 4, Funny

    I just wrote two programs to count to 1 billion. The one written in C took 2.4 seconds, the one written in assembly took 0.85 seconds. Wow, assembly is so much faster. My in-depth analysis of these two languages has shown once and for all that all us high-level language suckers need to get back to coding in assembly and quit this HLL foolishness.

    --
    "No one likes working in a hamster wheel, and your shop smells of cedar shavings from here." - TaleSpinner
  95. LEA! LEA! The guy's name is LEA! by fizzup · · Score: 2, Interesting

    LEA was "Load Effective Address" for the 8086, and it was a fast (and obscure, sidey-affecty) way to speed up a certain set of multiplication (and combo multiplication/addition) operations, which I now forget. Where's Abrash when you need 'im?

  96. Re:Can I have an infinite budget to write the code by kaffiene · · Score: 2, Interesting

    Almost exactly the same?

    C# doesn't have checked exceptions.
    C# allows the use of pointers.
    C# has pass by reference.
    C# has one major IDE (Visual Studio) which has a RAD philosophy which *does* prevent some valid C# code being written.
    C# has properties a-la Delphi
    C# isn't portable.
    C# has a bitmap class which is as slow as hell compared to the Java equivallent.
    C# has operator overloading
    C# doesn't have inner classes that can access the members of their container clases
    C# doesn't have anonymous classes
    C# has delegates

    There's just the differences I could pick off the top of my head.

    A lot of the really significant differences aren't in the core language (though there are a few of those, which mainly strip back the safety and simplicity that Java provides) but in the libraries and IDE.

    The IDE is really buggy and it forces RAD concepts on the programmer (shades of Delphi) which is a pain in the ass if you want to concentrate on code.

    There are *plenty* of reasons to like Java and not C# - they are *not* "exactly the same"

  97. Optimization at runtime vs. compile time by Get+Behind+the+Mule · · Score: 4, Insightful

    Whew, there's seems to be a lot of denial running through this thread. "An interpreted language just can't possibly be as fast or faster as a compiled language! So I just don't care what the empirical results say, no matter how badly or well done they are, it just can't possibly be!"

    I think some of you are overlooking the fact that a VM running byte code is capable of doing optimizations that a compiled language just can't possibly do. A compiled language can only be optimized at compile time. Those optimizations may be very sophisticated, but they can never be any better than an educated guess about what's going to happen at runtime.

    But a VM is capable of determining exactly what is happening at runtime; it doesn't have to guess. And thus it is able to optimize those sections of code that really are, in true fact, impacting performance most severely. In can do this by compiling those sections to machine code, thus exploiting precisely the advantage that a compiled language is alleged to have by its very nature. And other kinds of optimizations, the kind that a compiler traditionally does, can be performed on those sections as well.

    Of course there are scenarios where runtime optimization doesn't win much, for example in a program that is run once on a small amount of data and then stopped, so that the profiler doesn't get much useful info to work with. This is why Java is more likely to have benefits like this in long-running server processes.

    And of course a conscientious C++ programmer will run a profiler on his program on a lot of sample data, and go about optimizing the slowest parts. A conscientious Java programmer should do that too. But an interpreted language has the advantage that the VM can do a lot of that work for you, and always does it at runtime, which is when it really counts.

    1. Re:Optimization at runtime vs. compile time by Get+Behind+the+Mule · · Score: 2, Insightful
      Now, have you really thought this out?


      Sure have, friend, so let me respond with another question: Did you read my post? It seems that you've completely missed the point.

      First of all, I wasn't talking about Java and C++ so specifically, but rather about running byte code on a virtual machines vs. running machine code directly. When the VM is running byte code, it can profile the actual behavior of the program and optimize the sections that really are the slowest. A compiler that translates to machine code cannot do this, it can only guess at the best optimizations.

      Let's turn the languages around. Suppose we write a VM in Java, which runs byte code compiled from C++ programs. Then it can profile the running C++ byte code and optimize the critical sections. A C++ compiler that translates directly to machine code cannot do that.

      Understood this time?

  98. Benchmarks... by abertoll · · Score: 2, Insightful

    A langauge in and of itself does not determine the speed. It's how that language is implemented/compiled. There's no reason why Java SHOULD be slower as long as it is compiled to the machine's architecture, and not to byte code. ... but then that destroys the purpose of Java.

    --
    "he drew his sword Ringil that glittered like ice... and he wounded Morgoth with seven wounds..."
  99. Function calls by BenjyD · · Score: 4, Interesting

    Why does the example use a recursive fibonnaci sequence algorithm? It's so slow, and the runtime is dominated by the function call time.

    For example:

    [bdr@arthurdent tests]$ time ./fib_recurse 40
    165580141
    real 0m3.709s
    user 0m3.608s
    sys 0m0.005s

    time ./fib_for_loop 40
    165580141
    real 0m0.006s
    user 0m0.002s
    sys 0m0.002s

    I think a lot of these benchmarks are showing that the Hotspot optimiser is very good at avoiding function call overheads.

  100. Re:Sorry, no. by kraut · · Score: 3, Insightful

    >A VM otoh does get this capability for free.
    TANSTAAFL ;)

    > Java enforces garbage collection, and thus optionally gets the particular performance gain
    Err... whether garbage collection gains or looses you performance depends very much on your application. I am not convinced that any garbage collector can even be theoretically faster than automatic variables.

    >As was pointed out, one of the strenghts of C/C++ are pass-by-value....
    After programming in C++ for 14 years, I don't think I've heard that one before

    >The fact that you have to explicity declare a c++ parameter as pass-by-reference suggests that those interested in "good programming practices" (tm) will only make a pass-by-reference if you intend to modify it's contents
    const &? Ever heard of const references before? I don't feel qualified to judge your Java programming, but it's evident you're not particularly familiar with C++.

    I'd be interested to know how you have more control over the design of 3rd party libraries in Java than in C++.

    --
    no taxation without representation!
  101. Study Proves Sun Java Compiler Faster than GCC by xp · · Score: 4, Insightful

    Here is an excerpt from the article for this story: Lea used G++ (GCC) 3.3.1 20030930 (with glibc 2.3.2-98) for the C++, with the -O2 flag (for both i386 and i686). He compiled the Java code normally with the Sun Java 1.4.2_01 compiler, and ran it with the Sun 1.4.2_01 JVM. He ran the tests on Red Hat Linux 9 / Fedora Test1 with the 2.4.20-20.9 kernel on a T30 laptop. The laptop "has a Pentium 4 mobile chip, 512MB of memory, a sort of slow disk," he notes.

    What this shows is that GCC's implementation of C++ is slower than an interpreted language like Java. This does not show that C++ is slower than Java.

    ----
    Notes on Stuff

  102. Benchmarks? by slapout · · Score: 2, Informative

    It's not the benchmark's that count. It's the programs I need to run. Every program I've tried that's written in Java takes longer to start up than one written in C/C++. Althought that may change with .Net :-)

    Java has gotten better though. The programs are usable now days. (Just have that start up time as the virtual machine loads.) Use to be the programs loaded slow and ran slow.

    --
    Coder's Stone: The programming language quick ref for iPad
  103. Re:Caught up with the speed, but still the ugliest by Christopher+Cashell · · Score: 2, Insightful

    Actually, you're wrong, at least in part. Due to lack of specificity, I'd say that invalidates your argument.

    It's all about *where* and *how* Java is used.

    As someone who has done application development with both Java and C++ (as well as C, and others), here is how it works (assuming equivalent levels of code quality regardless of language):

    For a non-GUI application, Java can be made to run nearly as fast as C++, with a slight startup penalty, and while utilizing decidedly more RAM.

    For a GUI applicaton, Java will run considerably slower than a C++ application, and use significantly more RAM.

    What does this mean?

    Java works great for back-end applications, for web applications, etc. Especially if you take into consideration it's startup penalty (time needed to start the JVM) and run your java program persistently, Java can definitely be fast enough for this.

    As for GUI applications, Java is only an ideal choice if you absolutely need something that is fully cross-platform (without using multiple binaries for each), for small applications, or for situations where you can gaurantee that the client machine will have a LOT of RAM, and a fairly modern CPU.

    Now, use which ever langauge makes the most sense for what you're doing, and let's get back to coding, okay?

    --
    Topher
  104. More info, after some testing by Cthefuture · · Score: 4, Insightful

    I just went through and tested the hash2 benchmark and found that I was correct. The C++ version slaughters the Java version (even in "server" mode). This is completely different than what this dude's page shows.

    Here is the "correct" code for hash2.cpp:

    #include <stdio.h>
    #include <iostream>
    #include <ext/hash_map>

    using namespace std;
    using namespace __gnu_cxx;

    struct eqstr {
    bool operator()(const char* s1, const char* s2) const {
    return strcmp(s1, s2) == 0;
    }
    };

    struct hashme
    {
    size_t operator()(const char* s) const
    {
    size_t i;
    for (i = 0; *s; s++)
    i = 31 * i + *s;
    return i;
    }
    };

    int
    main(int argc, char *argv[]) {
    int n = ((argc == 2) ? atoi(argv[1]) : 1);
    char buf[16];
    typedef hash_map<const char*, int, hashme, eqstr> HM;
    HM hash1, hash2;

    for (int i=0; i<10000; i++) {
    sprintf(buf, "foo_%d", i);
    hash1[strdup(buf)] = i;
    }
    for (int i=0; i<n; i++) {
    for (HM::iterator k = hash1.begin(); k != hash1.end(); ++k) {
    hash2[(*k).first] += k->second;
    }
    }
    cout << hash1["foo_1"] << " " << hash1["foo_9999"] << " "
    << hash2["foo_1"] << " " << hash2["foo_9999"] << endl;
    }

    --
    The ratio of people to cake is too big
    1. Re:More info, after some testing by GooberToo · · Score: 2, Interesting

      I have not looked at the changed code, but I do reproduce your results:

      java-server: 14.93user 0.10system 0:15.67elapsed 95%CPU
      g++-O2: 8.10user 0.03system 0:08.38elapsed 96%CPU

      That places g++ about twice as fast as java, at that benchmark, assuming the code is correct. ;)

  105. Java Faster Than C++? by Dun+Malg · · Score: 2, Funny
    "Java Faster Than C++?"

    (/me runs screaming from soon-to-be-burning building)

    Is there something about flame-conducive subjects that make people want to "pick the scab", so to speak, or is it that sensitive subjects make people want to set stuff on fire? I think the Java vs. C++ holy wqar has even surpassed the EMACS vs vi one. (This is a good thing, I think, because arguing over vi vs. EMACS is a waste of time when it's clear that EMACS is better)

    --
    If a job's not worth doing, it's not worth doing right.
  106. String concat sillyness by danharan · · Score: 4, Informative
    The article mentions Lea modified the String concatenation code, although Java still lost to C++ in that test. He unfortunately didn't do a great job:
    import java.io.*;
    import java.util.*;

    public class strcat {
    public static void main(String args[]) throws IOException {
    int n = Integer.parseInt(args[0]);
    StringBuffer str = new StringBuffer();

    for (int i=0; i<n; i++) {
    str.append("hello\n");
    }

    System.out.println(str.length());
    }
    }
    Instantiating the StringBuffer with an approximate size would prevent it from having to reassign a char array every time it runs out of space. new StringBuffer(n*6) for n=10000000 as used in his test should have a pretty large impact.

    I could not run the test for 10M, but ran it for up to 1M. 541 milliseconds in one case, 280 in the other. Here's the code I used (I had to modify the timing cause I'm running XP):
    public class Strcat2 {
    public static void main(String args[]) throws IOException
    {
    long start, elapsed;
    start = System.currentTimeMillis();

    int n = Integer.parseInt(args[0]);
    StringBuffer str = new StringBuffer(n*6);

    for (int i=0; i<n; i++)
    {
    str.append("hello\n");
    }

    System.out.println(str.length());
    elapsed = System.currentTimeMillis() - start;
    System.out.println("Elapsed time: "+elapsed);
    }
    }
    The only difference in the class Strcat besides the class name is the instantiation of StringBuffer.

    NB: I'm not accusing the author of bias against Java, nor am I ignorant of the fact a bunch of /.'ers could kick my ass in C++ optimization. It would be interesting however to have a distributed benchmark, where in the true spirit of OSS we could fiddle with it until we could not wring any more performance gains.
    --
    Information: "I want to be anthropomorphized"
  107. Re:Caught up with the speed, but still the ugliest by Sivar · · Score: 3, Interesting
    Java might have finally caught up with the speed, but Swing is still the ugliest GUI out there.
    SWING performance didn't catch up to anything. SWING and SWT are still FAR slower than QT or the Win32 API but a long, longshot. SWING especially is absurdly, stupidly slow.

    Non-graphical Java code can indeed be very competitive with other languages, but it would help if the author bothered to implement the code for his tests intelligently.
    The Fibonacci code is recursive, which is about the slowest possible way to implement it, and much of the other code uses high-level features of C++ which are a convenience for the programmer, but are not used when worried about speed.

    This fibo code, for example, should be faster:
    const int max = 1000;

    void fibonacci (unsigned long num)
    {
    int fn = 1, fibo_array[max] = { 0 };
    fibo_array[0] = 1;
    cout << "1 ";
    {
    for(int i = 1 ; i < num ; i++)
    {
    cout << fn << ' ';
    fibo_array[i] = fn;
    fn += fibo_array[i-1];
    }
    }
    return;
    }
    This code was turned in by a student in a lab of mine. This was his first semester in CS, and this code outperforms the Java code quoted on the website considerably. (Try it!).

    I am not saying that recursion and high-level C++ features should NOT be used, but I AM saying that if you are comparing the potential speed of languages, you should use tricks that each language provides to optimize speed.

    Java will never be faster than properly optimized C++ compiled with an intelligent optimizing compiler except in bizarre corner cases, and tests like this are not terribly convincing demonstrations otherwise. Even the corner cases are removed by a sufficiently talented programmer.
    This is also not to say that Java is bad. I think Java is a great language (except for GUI programming with SWING), and definitely makes many programming tasks faster to code and easier to debug than one can do in C++.
    --
    Computer Science is no more about computers than astronomy is about telescopes. --E. W. Dijkstra
  108. Re:-O3? by BenjyD · · Score: 3, Informative

    Because -O3, despite what many people say, doesn't very often generate faster code. In many cases the extra inlining can create slower code.

    For example:

    methcall.cpp -O2 1.8s -O3 1.8s
    fib.cpp -O2 3.7s -O3 3.7s
    matrix.cpp -O2 1.8s -O3 1.8s (interestingly, adding -march=athlon-xp for my machine reduces time to 1.5s)

  109. Timing strategies by Adruab · · Score: 3, Interesting

    First of all, the C++ was crappy as many people pointed out.

    Second of all, I'm sure that loading the C++ program takes some time more than just loading the byte codes (though that's probably mitigated somewhat by the byte code translation).

    Third, the optimization options he used for gcc are a joke. -march=i686 is not even relevant to much larger platforms that can benefit from other optimizations.

    And, 4th, and this is the big one, this guy does not know how to benchmark. Anyone who has actually benchmarked their own application knows that if you want to figure out how fast something is, you have to time it IN THE PROGRAM!!!! This would avoid allocation/cout/unnecessary function overhead, when all you're trying to test is a specific operation. I BET (and at some point I will test this) that if you used timing mechanisms INSIDE the programs, that C++ would come out much faster, with the exception of object management and memory stuff (excepting garbage collecting...). Even then, much of that stuff can be overcome by memory pooling, which a surprising number of people ignore.

    Until someone does something like all these language comparisons are totally pointless because you are NOT ACTUALLY BENCHMARKING the topic you are looking at. Please lets have someone be intelligent about this for once....

  110. Obligatory Bash Quote... by MP3Chuck · · Score: 3, Funny

    http://bash.org/?338364 #338364 +(1308)- [X] Saying that Java is nice because it works on all OS's is like saying that anal sex is nice because it works on all genders

  111. Command and source/test review. by Ninja+Programmer · · Score: 4, Informative

    erm ... I only checked the fibonacci routine, but it's actually quite funny - he's branching recursive calls, a clear case when a smart-enough runtime optimization would work better. I mean, any reasonably smart optimizer would eventually figure out that there are too many calls to the same function with the same argument to just stand by and watch. I'd say that given this difference c++ did quite alright in that one.

    This is known as the "halting problem". No, the compiler cannot guarantee the ability to transform a recursive solution to a non-recursive one. The case of the fibonacci algorithm is a particularly difficult one to transform properly if the compiler hasn't special cased it.

    That said -- Ack and Fib are call overhead limited. They examples of poor quality code whose performance is not inner loop based.

    Hash will be C-string (specifically strcmp and sprintf) limited in performance. The performance is therefore very data dependent (since Java uses length delimited strings.) Using a fast string class such as "The Better String Library" (http://bstring.sf.net) would have yielded C++ far better performance. A similar comment applies to the strcat test.

    The Heapsort is a particularly bad implementation. In good implementations, the Intel compiler really takes gcc to town. See: http://www.azillionmonkeys.com/qed/sort.html

    Integer Matrix multiplying is an extremely rare application. So I wouldn't put too much stock in the results here -- though, I would be surprised if there was much differentiation between either Java of C++ on this test.

    The method calling, I think, will be very much limited by the compiler's ability to inline past method calls. I think Intel C/C++ differentiates itself on such things.

    The Nestedloop and random tests are interesting -- I don't see how Java is supposed to beat C++ on it, but its possible to be equal.

    I don't know enough about the Java object system and barely enough about C++ object system to comment on sieve or objinst.

    It seems to me that sumcol and wc are going to be IO limited.

    I don't think this test is exactly fair, as the code is not representative for tasks where performance really matters.

    1. Re:Command and source/test review. by arkanes · · Score: 4, Informative
      The method call is a really egregious case of bad methodolgy. The C++ test he's using was designed to test method call overhead, which is why it returns by value instead of refrence. The massive performance improvement from the JVM (server only, note) is the JVM aggresively inlining the call (and it's a single method call in a tight loop, an obvious inline candidate), so what he's measuring is just loop performance, not method call overhead. If he hadn't disabled loop unrolling and function inlining in GCC (via O2), C++ would have performed much better.

      It's worth pointing out that inlining is a case where a VM can really shine for optimizing because it has alot more options available (partial inlining, etc) and can make better decisions about tradeoffs. But this particular benchmark is comparing apples to oranges.

    2. Re:Command and source/test review. by norton_I · · Score: 4, Informative

      The method test is limited by two things: First, gcc appears unable to inline virtual method calls through a pointer to an object, even when the exact type is available, second, he didn't turn on loop unrolling. Loop unrolling is a huge, huge advantage on any sort of null benchmark like this.

      Changing the objects the be stack allocated and adding -funroll-loops moves the c++ benchmark up to just ahead of the java benchmarks.

      Of course, this does point to several advantages of a runtime optimizer. A static optimizer will never be as good at optimizing virtual function calls as a runtime optimizer, since it will never be as good at identifying types. Also, a runtime optimizer will always be better at creating specializations of existing functions (creating a special version of a routine when some input value is treated as a constant).

  112. Re:Can I have an infinite budget to write the code by Bryan_W · · Score: 2, Funny

    Why not just use VB? It would have been the easiest and probably faster.

  113. Java == modern COBOL by NotZed · · Score: 2, Interesting

    Java works well as a COBOL replacement, a backend application language for boring buisiness apps.

    Thats what it should be benchmarked against. Comparing it to C is like comparing apples and oranges.

    --
    _ // `Thinking is an exercise to which all too few brains
    \\/ are accustomed' - First Lensman
  114. hash.c uses sprintf which is very slow by Serveert · · Score: 3, Insightful

    sprintf(buf, "%x", i);

    It must parse the "%x" and determine what it's trying to do. So it decides, at runtime, you want to translate an integer value into a hexidecimal string. Of course if there's an error at runtime in the string "..." it must generate an error. How 'bout using strtol?

    Now let's look at the java version:

    Integer.toString(i, 16)

    Ok, here we have something that is strongly typed so of course it will be faster. At runtime the java compiler _knows_ what it's dealing with and it knows it must invoke the hexadecimal conversion code.

    Note that these statements are within loops.

    Just one example, that was the first file I looked at. I don't think they have quite optimized the C++ code IMO. Plus the C++ library is notoriously slow, I would recommend rogue wave or your homegrown C++ classes.

    I think the lesson here is it's very easy to write slow C++ code while it's very easy to write fast Java code.

    Gimme any C++ code here and I'll profile it/speed it up and get it as fast if not faster than java.

    --
    2 years and no mod points. Join reddit. Because openness is good.
  115. Java to Assembly by HopeOS · · Score: 3, Insightful

    It should also be mentioned that the java language requires specific overhead to be included that C++ and C do not. Even if compiled down to sleak assembly, Java is still saddled with doing bounds checking.

    The rest of the performance improvements are in the compiler optimizations and libraries which are mostly tangential to the language itself. If the compiler is clever enough to take "for (x=0, i=0; i<100; ++i) x+=5;" and substitute this for "x=500;", then great, but it should not be confused with an endorsement of the language itself.

    Furthermore, I had no difficulty modifying the C++ code to outperform or at least meet the results of the server-side JVM using G++. In the cases where Java had any lead whatsoever, the code was so trivial that the JVM could virtually precompute the result. I don't see this as being useful because in the real-world, nothing I write is so trivial that this is possible. If it was, I would have done it myself. I believe this largely explains the discrepency between these "tests" and my actual experience.

    -Hope

  116. Really? Try this one. by rjh · · Score: 3, Informative
    Given *any* algorithm, I can come up with a c++ implementation that is faster than a Java implementation. Period.
    I'd like to see a C++ implementation of the Halting Problem that's faster than a Java implementation, please, thank you.

    Oh, wait, you can't do that because nobody can write Halting.

    I guess that means there are some algorithms for which you can't write a faster C++ version. Next time, try less rhetoric and more facts. "There exist lots of algorithms for which I can code a C++ implementation that's faster than a Java implementation" is good. The instant you make a unilateral statement like the one you just made, though, it shows that you don't know as much about computer science as you think you know.

    Fact: there exist cases where Java is faster due to its ability to optimize on the fly. And if you know C++ as well as you think you do, this shouldn't surprise you. C++ beats C so handily for many tasks because C++ is able to do much better compile-time optimization largely on account of the C++ compiler having access to much more type information than a C compiler. When Java beats C++, it's on account of Java having access to much more information about runtime paths than a C++ compiler. ("Much more" may be an understatement; C++ doesn't even try!)

    In other words, the JVM (sometimes) beats C++ for the exact same reason that C++ almost always spanks C; the faster implementation has access to more information and uses that information to make more efficient use of cycles.

    I don't think these situations will appear all that often, and I am deeply skeptical of this guy's "in the general case, Java is faster" conclusion. But my skepticism isn't leading me to make rash statements which cannot be backed up.
  117. Re:Caught up with the speed, but still the ugliest by mangu · · Score: 2, Insightful
    Yes, of course, the recursive Fibonacci is slow. But the point was measuring the efficiency of the compilers, not the efficiency of the code. Do you want a much faster Fibonacci algorithm? Here it is:


    double gold = (1.0 + sqrt(5)) / 2.0;


    int fibonacci(int n)

    {

    return floor(gold * n);

    }

  118. One mistake (Was: Re:Explanation) by jdennett · · Score: 2, Informative

    Almost no C++ implementation calls the OS (kernel) for every memory request, precisely because that's too slow.

    More to the point, C++ doesn't *have* to use dynamic allocation so often, but in badly written code it may well do so, and that will hurt performance. In C++ you can drop objects on the stack, in Java you can't. Heap/GC allocation can be pretty quick, but not quite as quick as stack allocation.

  119. Java performance "truths" change over time by eduardodude · · Score: 5, Informative

    Check out this recent IBM Developerworks article which looks at how modern JVMs handle allocation and garbage collection.

    Some very surprising tidbits there. For instance:

    "Performance advice often has a short shelf life; while it was once true that allocation was expensive, it is now no longer the case. In fact, it is downright cheap, and with a few very compute-intensive exceptions, performance considerations are generally no longer a good reason to avoid allocation. Sun estimates allocation costs at approximately ten machine instructions. That's pretty much free -- certainly no reason to complicate the structure of your program or incur additional maintenance risks for the sake of eliminating a few object creations."

    Read the article for an excellent nuts-and-bolts analysis of many current performance considerations. From the posts in this thread, it's pretty clear a lot of people haven't looked into what's actually done in a server JVM these days.

  120. Re:Sorry, no. by maraist · · Score: 2, Insightful

    While you make several good points. I do have some counter-points.

    A VM otoh does get this capability for free.

    Let me qualify this as saying you don't have to do or pay for anything extra to achieve this.

    Err... whether garbage collection gains or looses you performance depends very much on your application. I am not convinced that any garbage collector can even be theoretically faster than automatic variables.

    By automatic, if you mean stack-resident variables, then I agree (with the caveat of dangerous code design), but if you mean malloc'd variables, then I don't see what the problem is. malloc has to worry about a great number of things, not least of which is memory fragmentation. I happen to have done a non-trivial amount of research on memory allocators; though I am no expert. Memory allocators can be optimized for allocation speed, fragmentation efficiency, concurrency, cache coherence, etc. but not all (obviously). As it happens, a copying garbage collector gives you all of the above EXCEPT when your buffer runs out; and thereby requires a garbage collection. So long as you you have large heap and you're not worried about the latency from garbage collection, then copying collectors are VERY fast. Allocation is literally a mutex lock, a stack-pointer range check, a stack-pointer increment, then a mutex unlock.

    Now, because latency is often a real issue, most modern GC's apply additional complexity/logic which slows down the normal case to minimize the worst case; e.g. generational garbage collection which may require read or write boundry op-codes inserted. But code-wise, these varients are identical. Thus you achieve a flexibility not possible in a dynamic-memory-egnostic system such as c/c++.

    I'd be interested to know how you have more control over the design of 3rd party libraries in Java than in C++

    I didn't really mean design, but environment; Specifically in terms of the dynamic memory allocator. But, just to make the differentiation complete, java allows byte-code load-time modification. This is very common in "aspect oriented programming" such as in the database realm (JBoss/OJB) or object proxying. In Java, by introspection you can prepend/append/search-replace method calls or even individual instructions as need be. Note that this isn't any different than a custom pre-processor for C, but tends to be cleaner and thus doesn't require the [3rd party] coder to adhere to a particular convention.. Moreoever, this works on already shipped binaries, as opposed to requireing preprocessing to occur on the original source code.

    --
    -Michael
  121. However, C++ is faster to LEARN than java by RLiegh · · Score: 2, Funny

    at least if you already know C.

  122. C++ 60X Faster Than Java by Zan+Lynx · · Score: 2, Interesting
    I was confused by this article, because I know Java is slower than C++. I took one of the programs, the Ackermann function, and figured out what was happening.

    The Ack function was being called over and over with the same arguments. A little work with an STL map, and I created a cache for the function arguments and results. I think this is called memoizing a function.

    Here are the results when I finished:
    $ time java -cp java ackermann 13
    Ack(3,13): 65533

    real 0m29.620s
    user 0m25.180s
    sys 0m0.292s

    $ time ./ackermann 13
    Ack(3,13): 65533

    real 0m0.479s
    user 0m0.228s
    sys 0m0.017s
  123. Same for hash.cpp by Tim · · Score: 4, Interesting

    I'm futzing around with the other hash benchmark, and sure enough, making only a trivial change to the code (eliminating the unnecessary strdup in the second hash lookup), gets me about a 30% improvement in performnace.

    This guy is a tool.

    --
    Let's try not to let fact interfere with our speculation here, OK?
  124. That's all true.. by mindstrm · · Score: 2, Insightful

    but that's nto the same thing as saying "Java is faster than C++". The benchmarks in question are bout execution speed, not development speed.

    Some of the benchmarks could have been far better implmented with code no more complex than what was arleady used on the c++ side... that's the issue here.

    "java is faster for lazy coders" is a fair statement.. but not really what a benchmark tries to asess.

  125. Not silly at all by GCP · · Score: 3, Interesting

    I don't deny that the finer granularity of C++, no make that plain C, no make that raw assembly language, allows you to make certain optimizations that are quite valuable in certain circumstances.

    But when you are trying to choose the right tool for a particular job, you need to be current on the details of just what advantages, and what degree of advantage, and in what circumstances, comparing current versions of all of the candidate tools.

    This benchmark seems to be showing that things don't just remain the same. That, in fact, the circumstances in which C++ is a better choice than Java are becoming fewer and the advantage in those circumstances is becoming less.

    The fact that Java VMs are primarily written in C or C++ indicates that at the time they were initially written, it was believed (I think correctly) that the C or C++ at that time would be a better platform for writing JVMs than the Java of that time, and that since then it has been considered better to extend the existing code than to scrap it and do a complete rewrite in Java.

    That's all that this argument proves. Nothing more.

    What I'm saying, though, should not be interpreted as a belief that today's Java would be a better choice than today's C++ for writing a Java JVM. I don't know what the relative advantages would be today.

    But if C++ were STILL the best tool for writing a JVM from scratch today (certainly possible), that wouldn't mean much when trying to choose a tool for your own app, because most apps bear very little resemblance to a JVM.

    --
    "Those who have never entered upon scientific pursuits know not a tithe of the poetry by which they are surrounded."
  126. never underestimate the cost of stream sync by emarkp · · Score: 2, Insightful
    The cout is done twice, and the new and delete are each done only once. They are not the reason for the poor performance.

    Sure cout is done twice, but it uses 'endl' where '\n' would do. 'endl' flushes the stream, which pretty much kills cache behavior. When the disk/console is orders of magnitude slower than the CPU, a single 'endl' can indeed kill performance.

    As for new/delete, they can also be very slow, depending on the current memory layout, etc. More importantly, they violate the C++ programming paradigm (local objects not allocated on the heap) and hence are indicators that this isn't a very good C++ programmer, and hence he isn't qualified to make a reasonable comparison.

    Shoot, the last time I did the Java/C++ flamewar I found that Python was faster than both (reading and sorting strings).

  127. you have no idea what you're talking about by autopr0n · · Score: 2, Informative

    Are you trolling or what?

    This is known as the "halting problem". No, the compiler cannot guarantee the ability to transform a recursive solution to a non-recursive one. The case of the fibonacci algorithm is a particularly difficult one to transform properly if the compiler hasn't special cased it.

    No it's not. In fact, it's not even close to the definition of the "halting problem". The Halting Problem is "Given input X, and program Y, will Y ever finish it's calculation, and halt on when given X as an input". It's a 'problem' for which no computer program can be written to solve.

    It has nothing to do with whether or not a compiler can convert a recursive algorithm into a non-recursive one.

    That it's possible to convert looping programs into recursive programs is trivially true, because recursive functions alone are Turing complete. Similarly, because any recursive program can run on a Turing machine, which has no concept of a 'stack' needed for recursive calls can run any recursive program by emulating the stack on it's tapes.

    If you want a real world example, just compile any recursive code in any language to MIPS or some other RISC instruction set without push/pop and call functions like those found on X86 chips. You don't "call" functions directly, you just move around in memory and jump all over the place, just the same as you would in looping code.

    --
    autopr0n is like, down and stuff.
    1. Re:you have no idea what you're talking about by Deliberate_Bastard · · Score: 3, Insightful

      I'm sorry, but I am afraid you are wrong.

      Well, I know the halting problem and I don't see how it relates to what you're saying. The conversion from recursive to iterative isn't arbitrarily complex, it's simple and mechanical. The easiest way is to simply use a stack to maintain the state of what were previously recursive calls.

      This is still recursion. You have simply substituted one stack for another.

      Anyways, all the halting problem implies is that an optimizer will never be able to find every situation where a particular optimization is applicable.

      No, it implies much more than this.

      Deciding whether two programs are equivalent(EQTM) is equivalent to ATM (the halting problem). (I'll give the series of proofs if anyone requests it.)

      This means that there is no algorithmic way to transform recursive functions into iterative ones, and any substitution must be based upon matching of patterns pre-coded into the compiler.

      --
      NOTICE: This notice will appear at the bottom of all my slashdot posts.
    2. Re:you have no idea what you're talking about by Deliberate_Bastard · · Score: 2, Insightful

      Your other assertion here is that a recursive algorithm rewritten iteratively is still recursive if you don't do anything more complicated than maintain the state with a stack. Well this is not true. A function that does not invoke itself is not recursive, period.

      Depends how you define recursion. The prescence of a stack which maintains states means that the function *is* invoking itself. It's just doing so in the same frame on the main stack.

      Externalizing the stack *is* more effecient. But it is still, in any meaningful sense of the term, recursive.

      In fact just by looking at some (non-recursive) function that uses a stack, and judging that it could obviously be rewritten as recursion, you are finding an equivalance between them, which according to you is impossible.

      You have misunderstood the meaning of the term "undecideable". Please see my other reply for the details of how this works.

      --
      NOTICE: This notice will appear at the bottom of all my slashdot posts.
  128. K5 doesn't allow new user sign-ups by tepples · · Score: 2, Informative

    At last count, Kuro5hin was closed to new users. Therefore, K5 is not a general purpose discussion site. New users have mostly gone to K6 instead.

  129. ABI compatibility by tepples · · Score: 2, Interesting

    It's a benchmark. We're benchmarking performance.

    Correctness comes before performance. Failing to link at all by no means produces good performance because a test of performance on incorrect code is an invalid test. Using one C++ compiler to compile your system libraries and another C++ compiler to compile your applications will often result in either failure to link or incorrect code because of subtle ABI (application binary interface) differences among C++ implementations.

    On the other hand, the Java platform ABI is well-defined for several years now.

    And would you grant that the benchmark is a valid test of Sun's implementation of the Java language vs. the G++ implementation of the C++ language?

  130. Re:Sorry, no. by maxwell+demon · · Score: 2, Funny

    Well, actually, an ideal optimizer would detect that this loop has no observable behaviour, and therefore optimize it away completely. That is, the complete loop would be compiled to zero instructions and executed in zero time. Of course, a perfect Java compiler could do the same, which of course gives the question of how many times faster Java zero time is to C++ zero time :-)

    --
    The Tao of math: The numbers you can count are not the real numbers.
  131. FAIL YOUR STUDENT by EventHorizon · · Score: 2, Funny

    And tell him to check for buffer overruns next time (num > max).

    On the plus side: after he flunks out, he can go write RPC code at Microsoft.

    Or, perhaps, a cell phone bluetooth stack.

    [Ducks And Covers]

  132. PCs are LBAs, and Halting for LBAs is solved by tepples · · Score: 2, Interesting

    If you hand me a correct algorithm for the halting problem, I'm sure it could be coded in C++ so it ran faster than in Java.

    A Turing machine modified to have a limited-length tape is called a Linear Bounded Automaton (LBA). A PC is equivalent not to a Turing machine but to an LBA. There does exist a correct algorithm for the halting problem when applied to LBAs: emulate two copies in a tortoise-hare configuration and look for loops in their state.

  133. Re:Really? Try this one. by cardshark2001 · · Score: 2, Insightful
    I'd like to see a C++ implementation of the Halting Problem

    Eh.... so for your counter example you choose a problem that is unsolvable in any language?

    Did you just read about that in your computer science class or something? How does that relate to the question at hand? For any java implementation, of any algorithm, I (or someone else) can write a c++ implementation that is faster. Does this mean that I can solve problems in c++ that are unsolvable? Ummm.... no.

    This is a common logical fallacy. Its Latin name is "Non-Sequitur". You'll probably get to that next year when you study logic.

    --
    WWJD? JWRTFA!
  134. Write a JVM in Java??? by Ytsejam-03 · · Score: 2, Insightful
    The fact that Java VMs are primarily written in C or C++ indicates that at the time they were initially written, it was believed (I think correctly) that the C or C++ at that time would be a better platform for writing JVMs than the Java of that time, and that since then it has been considered better to extend the existing code than to scrap it and do a complete rewrite in Java.

    That's all that this argument proves. Nothing more.

    What I'm saying, though, should not be interpreted as a belief that today's Java would be a better choice than today's C++ for writing a Java JVM. I don't know what the relative advantages would be today.
    Am I missing something, or did you just suggest writing a JVM in Java? Which language will you use to implement the JVM that will run your Java-implemented JVM?

    My understanding is that JVM performance has improved because they are now doing things like selecting the appropriate instruction set for the processor at runtime. This is opposed to natively complied languages which are typically compiled to support the lowest common denominator.
    1. Re:Write a JVM in Java??? by ArsenneLupin · · Score: 2, Informative
      For example, the GCC compiler can compile its own source code.

      Yes, the GCC compiler. However a JVM is an interpreter.

    2. Re:Write a JVM in Java??? by elhaf · · Score: 2, Interesting

      Yes, and Java is a language. Your point? Java is turing-equivalent. According to the Church-Turing thesis, anything computable can be written in Java. Including a JVM. One does need to execute that JVM, of course, but that's true of any bootstrap operation. It is possible to compile java to native code; JIT's do it all the time. C still needs some assembly routines at startup to run, and it relies on a BIOS underneath. If you want a real mind-bender on this subject, look into Futamura projections for some fun.

      --
      Six score characters.
      Brevity being wit's soul
      I have enough space.
  135. Tools by Myolp · · Score: 2, Insightful

    Something that is almost always ignored when comparing programming language is the actual cost of developing something in that language.

    Sure, you can almost always produce faster software in a low-level language. But since there are no good tools for doing this, it costs to much. Developing software using a modern, state-of-the-art IDE like IntelliJ IDEA, NetBeans or Eclipse speeds up the actually development process and allows the programmers to focus on the design, rather than trying to understand an obscure low-level API.

    And no, Visual Studio does not count as a state-of-the-art IDE...

    1. Re:Tools by SnapShot · · Score: 2, Insightful

      Similarly, something this is also almost always ignored when comparing languages is the actual cost of developing something using the libraries available to that language.

      Back in the dark ages (late 80's) I learned to program in Basic, then Pascal, then ADA, then C, then C++ through high school and college. It must of been 8 years of part-time messing around with code before I wrote my first GUI (I luv that MFC!!!).

      Two days after picking up a Java book, I was doing (crappy but they worked) GUIs in Java.

      Two days after that I had database access through JDBC.

      Then is was XML parsing.

      Then is socket communication.

      Then J2EE...

      With every one of these libraries, a critic could potentially have a complaint that "Sun's implementation of X isn't nearly as good as library Y". However, they are available for free to any developer who has Java, they are documented in a thousand books about java, and the Javadoc web pages make sure there is a common way to access the knowledge necessary to learn new features.

      That, I think, is Java's greatest strength. Sure, Qt, Fox, MFC, GTK, Win32, or whatever may be a better (in your opinion) GUI library, but Swing is available to anyone who programs Java on just about any platform. I bet there are some custom ODBC-like drivers that squeeze the last ounce of performance out of your database system, but I bet I can have database access implemented in Java befor you have managed to get the purchase request for your ODBC library past the financial people.

      So, leave the arguments on who can leverage the last performance boost out of a language to the Comp. Sci. PhDs and researchers. If you, like me, are working in a business environment where success is measured in getting a working product out the door that meets the client's requirements, focus on the libraries you have available rather than the language. By that metric, Java comes out near the top.

      --
      Waltz, nymph, for quick jigs vex Bud.
  136. Re:Some performance myths by dtfinch · · Score: 2, Interesting

    First of all, g++ actually sucks big time in terms of performance.

    Just in this case, it sucked much more than usual. -O2 is no match for something that does automatic loop unrolling and function inlining. And the loop unrolling doesn't even get enabled in -O3. My own preference is to start with O3 and enable loop unrolling and omit-frame-pointer, which seems to make a noticeable difference.

  137. Re:at risk of sounding like microsoft... by nevets · · Score: 2

    In a lot of cases, you are right. But some of us (me included) work on military or other complex systems that getting 10 percent faster output would be great. I find that there is a lot of effort going on to put as much as posible on the smallest amount of hardware. The system may be fast, but the work load is going up, since to make things lighter, you run five apps that use to run on five different machines, on a single unit. One project switched to Java and is now suffering from performance issues. Now the code needs to be redesigned to get the required output.

    Speed will always matter, until we solve those nasty NP problems ;-)

    --
    Steven Rostedt
    -- Nevermind
  138. Looking as the assembly for the C++ code by mc6809e · · Score: 3, Insightful

    I notice that much of the overhead is simply in making function calls.

    Ackermann.cpp, for example, spends very little time actually calculating anything. Much of it's work includes all the overhead associated with making a function call.

    Included in this overhead is management of the frame pointer. By using -fomit-frame-pointer, you avoid pushing the old ebp on the stack and a store of the current esp into ebp.

    Ackermann runs about twice as fast with this simple optimization.

  139. Bullshit by baest · · Score: 3, Insightful

    I saw this test a few days ago and wanted to check it out. The first thing I realize is that the source code is somewhat different even if Java has almost the same syntax as C++.

    I understand that System.out.println(); is not in C++ but why have

    return(M ? (Ack(M-1,N ? Ack(M,(N-1)) : 1)) : N+1);
    instead of
    return (m == 0) ? (n + 1) : ((n == 0) ? Ack(m-1, 1) : Ack(m-1, Ack(m, n - 1)));

    I made the C++ code look like Java and got a 15% save. Problably even more if I had increased the number you call the program with. I looked at some of the other program and they have different code in them as well. So this test is bullshit it only shows that you can make slow programs in any language.

  140. Let's see the primes thing again :-) by RedlumF · · Score: 2

    Ok, here is the java version
    [alex@alkis dev]$ time
    /usr/bin/j2sdk1.4.2_04/bin/java -server sieve 10000
    Count: 1028
    1.94user 0.02system 0:02.08elapsed 94%CPU (0avgtext+0avgdata 0maxresident)k
    0inputs+0outputs (1major+2392minor)pagefaults 0swaps

    And let's see the g++ ...
    [alex@alkis dev]$ g++ -O2 -o sieve sieve.cpp
    [alex@alkis dev]$ time ./sieve 10000
    Count: 1028
    7.64user 0.02system 0:07.84elapsed 97%CPU (0avgtext+0avgdata 0maxresident)k
    0inputs+0outputs (0major+264minor)pagefaults 0swaps

    Should we try intel's c++ compiler?
    [alex@alkis dev]$ icc -O2 -o sieve sieve.cpp
    [alex@alkis dev]$ time ./sieve 10000
    Count: 1028
    0.90user 0.00system 0:00.94elapsed 97%CPU (0avgtext+0avgdata 0maxresident)k
    0inputs+0outputs (0major+284minor)pagefaults 0swaps

    Now, can someone compile KDE/Qt with icc and send it to me, please?
    Thank you!

    /Alex

  141. the halting problem is related by muyuubyou · · Score: 2, Interesting

    If you convert in the simple and mechanical way you mention, you are not going to improve the efficiency of the algorithm at all. You wouldn't be doing anything else but what the computer is doing by it's hardware stack (which would probably be faster via hardware optimizations).

    What we're talking about here is converting recursive to iterative without using the friggin' stack. That would be finding a mathematically equivalent function that is not recursive. This looks pretty much equivalent to the Halting Problem, or Rice's Theorem for that matter. Trivial for a person in some cases like this, but not easy to generalize.

    If there are heuristics to do that effectively, that I don't know. I will check that document you link to when I have the time.

    In this case, result caching would do. Result-caching takes memory but it makes sense sometimes (not that often, mind you). One of the problems I see here is memory efficiency isn't considered at all. It's ok if your machine is 100% dedicated to a fancy benchmark, but running some memory-hungry java processes like this in parallel would make your computer start thrashing to the HD to a virtual halt.

  142. Server-side close but GUIs will keep the by mactari · · Score: 2, Insightful

    What's important to note is that the differences introduced by the VM and the rest of Java's overhead are small enough now that, for headless applications, poor coding can easily bridge the difference. There's no huge, glaring, a priori reason to use C++ over Java for headless apps, and when you want your server code to be portable crossplatform you'll find a huge, glaring reason to use Java.

    Now what this study obviously doesn't deal at all with GUI'd applications, and Sun's Swing in particular does nothing to help Java's reputation as a slow technology. There's a relatively interesting discussion at java.net called Swing Usability that points out some of these shortcomings. What the Swing team doesn't seem to understand is that slower than native means slow to most users.

    And just like the comments in this thread point out, as long as you put a compatibility layer between code and execution, you're going to be slower by definition. With Swing, simple to overlook unoptimized coding practices do not easily spell the difference between implementations. Here, Java's speed and performance is visibly slower no matter how quickly the GUI-less logic behind is racing along. (Yes, SWT is a big help, but it's not part of the JDK and likely still won't be seen in, say, Limewire any time soon.)

    --

    It's all 0s and 1s. Or it's not.
  143. Re:Really? Try this one. by CoughDropAddict · · Score: 2, Insightful
    Given *any* algorithm, I can come up with a c++ implementation that is faster than a Java implementation. Period.
    I'd like to see a C++ implementation of the Halting Problem that's faster than a Java implementation, please, thank you.

    Oh, wait, you can't do that because nobody can write Halting.

    I guess that means there are some algorithms for which you can't write a faster C++ version.

    Actually his statement still holds. No algorithm exists that can decide the halting problem, so he can still say "for all algorithms, a C++ implementation can be written that is faster than a Java implementation."

    But don't let me get in the way of you admiring how wise you are.

    Next time, try less rhetoric and more facts. "There exist lots of algorithms for which I can code a C++ implementation that's faster than a Java implementation" is good. The instant you make a unilateral statement like the one you just made, though, it shows that you don't know as much about computer science as you think you know.

    Get off it. Apparently you don't know as much about logical reasoning as you thought, or even Computer Science since you tried to call the halting problem an algorithm. Not to mention that the word "unilateral" makes no sense in this context; you probably meant "unequivocal" or "unqualified." Shall I find more things to pick on?

    (Normally I wouldn't be this pedantic, but you are ripping on someone else based on pedantry and being rewarded with +5.)

    Fact: there exist cases where Java is faster due to its ability to optimize on the fly.

    The whole point of this critique is that any run-time optimization that Java can perform, a human can perform when they write the algorithm. In the end, all programs are executed by running machine instructions, and any set of instructions that a JVM emits/executes, a human can write manually to achieve exactly the same performance.
  144. bootstrapping by GCP · · Score: 2, Interesting

    Many compilers and interpreters are written in themselves. Read the other comments about bootstrapping. And how do you think the first C compilers were written? In C?

    When you understand bootstrapping, you'll understand how one would create a JVM written in Java. (IBM did just that.) It's not a question of whether it is possible, but what the pros and cons would be.

    --
    "Those who have never entered upon scientific pursuits know not a tithe of the poetry by which they are surrounded."