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.""
The Java is Faster than C++ and C++ Sucks Unbiased Benchmark
"...the more people who know about present-day Java performance, the better."
This person will never know how right they were!
Java Rulez!
Correct link
how does it corner?
No, it isn't. It's much slower.
I wrote a program that simply counts to 10000 and then quits. Time from double-clicking the icon until when the program exits:How hard is that?
... C++ is more portable.
no one should ever run the client JVM when given the choice
If you don't run the JVM, how do you run your code?
Fact: C++ is dying....
Oh hell, I don't have the heart. Nevermind.
Quantum materiae materietur marmota monax si marmota monax materiam possit materiari?
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
The great thing about language benchmarks is that there are so many to choose from...
i tried to get first post with my C++ autoposting application...but its too damn slow.
Are there any sizable 3D games, i.e. code that really needs performance written in Java?
I just happened across Sun's FAQ about the -client and -server settings .
And Microsoft is more stable than Linux.
...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.
Java uses Star Trek Transporter technology! To beam cows no less (front page of java.com, right now).
What's C++ got? Grappling hooks?
--------------------- -me, Crusher of those who are Foolish (don't be foolish)
Just see what comes out of profiling this:
int main( int argc, char **argv )
{
for ( int ii = 0; ii < 10240; ii++ {
cout << ii << endl;
}
return( 0 );
}
Now compare it to this:
int main( int argc, char **argv )
{
char s[ 2 ];
s[ 1 ] = '\n';
for ( int ii = 0; ii < 10240; ii++ {
s[ 0 ] = '0' + ( char ) ii;
write( 1, s, 2 );
}
return( 0 );
}
Guess which one's going to be several orders of magnitude faster?
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.
The benchmarks page is down. I'm getting the 'slash hole' page. Does anyone know what these benchmarks are? And, is it an accurate comparison between the object-oriented nature of Java vs. C++ (which, as far as I've done, doesn't really have true oo support)?
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.
When the following two pieces of code are written in Java, I'll take it seriously:
1) a java compiler for java (funny that the java binaries are written in C++ and compiled with a compiler written in C++)
2) id's next game engine
https://www.accountkiller.com/removal-requested
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.
If you care about run-time speed when using gcc you compile with -O3.
I'd like to see the benchmarks redone with this.
This is gonna be mean.
"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.
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.
...but accordiing to the unbiased and objective Microsoft study, Java under Linux on a 3090 mainframe is still more expensive to run than NT Server 5 on a whitebox machine with dot net. What do they say to that? Hell, I'll stick with coding in whitespace. What do y'all think of this routine: K
The Kai's Semi-Updated Website Thingy
Oh... and as of Java1.5, Swing apps can now be skinned to look however you'd like them to.
File under 'M' for 'Manic ranting'
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.
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
Im 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 shouldnt be taken seriously.
-----
One is born into aristocracy, but mediocrity can only be achieved through hard work.
You were running Swing with the Windows L&F.
"There is more worth loving than we have strength to love." - Brian Jay Stanley
what i want to know is how did they run the benchmark without the java virtual machine.
i'm sure "command not found" is worlds faster then a loop in C++.
But seriously...this is entirely dependent on code design. Java people and C++ people are terrible at it (else how could they like these languages?). And I'm not about to RTFC to find out how they cooked this one up.
that know about present-day java performance, the more people will use java. is that really "the better?"
Compared to similar applications written in real languages (meaning any language that is not java) they are crash prone, give idiotic debug statements, suck up memory and easily get the "too many open files" error on linux.
I guess this is like "Windows nowadays is very stable" bit. You can show all the benchmarks and tests but I will let my daily experience be the judge and use reports such as this as the toilet paper it is.
To be fair, freenet does work on linux and windows as does Azureus. This is for me the only selling point.
Perhaps java is faster then C++, it is hard for me too judge. But until Java developers start writing better programs, Sun makes sure Java is really cross platform, and games (the ultimated performance applications) start being written in java I will file this with all the other reports on how java will take over the world and is the best, fastest, easiest.
MMO Quests are like orgasms:
You may solo them, I prefer them in a group.
I'll explain the joke for the moderators: He is incurring the overhead of launching the JVM, which is significant. In fact, all this tests is that invocation overhead and nothing else.
Lasers Controlled Games!
That's Great! I can't figure out GCC's error messages, but I offer definitive proof that Java is faster than C++. Nice.
In terms of speed it is un debatable that C is faster than Java because the jvm is written in C and execute bytecode which no matter how intelligently refactored will create one more level of indirection that lets pure C be faster.
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.
Looks like you haven't changed a bit!
ever discovered with Java: 1 (still waiting on that next one, I guess it's garbage-collecting) Can we build a grid-based garbage collector?
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.
Need a Python, C++, Unix, Linux develop
One of the best things about OS X is Aqua-ized Java apps.
o nc eptual/Java141Development/UI_Toolkits/chapter_5_se ction_2.html
http://developer.apple.com/documentation/Java/C
-- Have you ever imagined a world with no hypothetical situations?
This means nothing.
That is the most typical benchmark of somebody who doesn't know anything about compiler optimization.
This is almost truly a mark on the compiler making an optimization in one case where the Java compiler doesn't. Assigning to an unused variable is a useless operation. A decent compiler removes the assignment, then notices an empty loop, then removes the loop.
Not to mention, your double-click takes into account the entire VM initialization, which greatly, greatly outweighs the test itself, rendering the test useless on that account as well.
So you end up benchmarking the entire VM initialization with a NOP. Gee, wonder which one's going to win?
This is why benchmarks are hard. This is why the SpecINT benchmarks are notoriously bad as they (at least were) easy to optimize against.
By the sounds of it you have no idea what a good GUI is. Skins and themes do not a pretty UI make.
We used to simulate our computer architecture projects in our graduate studies and often noticed java code to be very very slower than C++. Even the superscalar processor code is written in C++. Ultimately I feel whatever these tests show people find C++ easier and faster to develop good simulation software and overall much better.
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.
i use debian, probably the same way it effects me, but years later.
IL2 Sturmovik is mostly Java. IIRC, only the rendering itself was done in native code for performance. With the advent of JOGL, even that can probably be done well in Java.
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.
The Great Computer Language Shootout
... and it's still growing with no end in sight (so be sure to read the NEWS). I'm doing it so that I can learn about new languages, compare them in various (possibly meaningless) ways, and most importantly, have some fun.
Back to the Language Shootout
Back to Doug's Homepage
[NEWS] [Editorial] [FAQ] [Methodology] [Performance Tips] [Download] [Activity Log] [Acknowledgements] [Scorecard] [Slash-Holed] [Rules for Benchmark Writers] [Conclusion] [Todo]
Hi, the shootout is an unfinished project. I've decided to discontinue updates to it for now while I work on some other things. Thanks for everyone's help.
[ 30 Language Implementations, 25 Benchmark Tests, 750 Total Possible Programs, 632 Written ]
Here's a list of which solutions have/have not been implemented.
The Benchmark Tests
Ackermann's Function
Array Access
Count Lines/Words/Chars
Echo Client/Server
Exception Mechanisms
Fibonacci Numbers
Hash (Associative Array) Access
Hashes, Part II
Heapsort
Hello World
List Operations
Matrix Multiplication
Method Calls
Nested Loops
Object Instantiation
Producer/Consumer Threads
Random Number Generator
Regular Expression Matching
Reverse a File
Sieve of Eratosthenes
Spell Checker
Statistical Moments
String Concatenation
Sum a Column of Integers
Word Frequency Count
(Not all languages are tested in every benchmark)
Other Language Comparisons
Creating Binary Extensions
(These are non-performance language comparisons)
A benchmark comparison of a number of programming languages.
Note: If you want a copy of the shootout, please get it from the Download Page, but please do not hammer my server requesting every page. The shootout tarball is updated nightly. Thanks.
Intro
When I started this project, my goal was to compare all the major scripting languages. Then I started adding in some compiled languages for comparison
Someday, maybe, the results I present might even be meaningful, but please take the current results with a grain of salt. You might get different results on a different OS, on different hardware, with newer releases of the languages, or even from run to run of the same test. You might even find that I have horrible bugs in my testing method.
This is very much a work in progress, as it evolves I may add, change or remove languages, tests, or solutions. Some solutions as currently presented are unoptimized, and may be optimized in the future (if I can do it myself or if someone contributes a better solution).
Disclaimer No. 1: I'm just a beginner in many of these languages, so if you can help me improve any of the solutions, please drop me an email. Thanks.
Disclaimer No. 2: These pages are provided for novelty purposes only. Any other use voids the manufacturer's warranty. Do not mix with alchohol. Some contents may consist of recycled materials.
Disclaimer No. 3: ditto.
Disclaimer No. 4: Please read the pages on Methodology, the FAQ, and my Conclusion before you flame.
By the way, the word Great in the title refers to quantity, not quality (I will let the reader judge that). I saw a need for a more comprehensive language comparison than what I could find out on the Net, and you are reading my solution. I wanted to see a comparison of more languages doing more tests, and with (hopefully) the participation of more people.
Aldo Calpini has put a huge amount of work into porting my shootout to Microsoft Windows. He even includes some new languages and some commercial compilers that run on Windows. Please click here to check it out. (Please note that there may be some differences in his port. It is really a separate, derivative work). Many thanks to Aldo!
The Languages
Language Imple-
mentation
(local summary) Version
(Official Homepage)
1. Awk gawk GNU Awk 3.0.6
2. Awk maw
There's at least one well-known game, something about Vampires, for the PC that used Java for the behavior engine.
As for the 3D engine, of course you want that optimized and you'd proably not want ot use Java - though you could if Java 3D had been improved. I odn't think that every was a well defined spec.
"There is more worth loving than we have strength to love." - Brian Jay Stanley
Tatoo: Boss, who's that?
Mr. Rourke: We have here Mr. Java. He has come here to live out his fantasy of being the fastest programming language around. Even faster than C++, but he will discover much more.
Tatoo: What will he disover, Boss?
Mr. Rourke: He will discover that he is in fact so slow that the only women he will be able to satisfy are the Granola PETA Vegan lovers that plague the Java world.
---
Everyone takes thier drinks, including Tatoo and Mr. Rouke
---
Mr. Rourke: I welcome you all to FAN-tasy Island! And may you all get it shoved up the ass!
Am I the only one who thinks michael uses Slashdot to post stupid crap that just supports his own uninformed bias?
--Matthew
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.
*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.
Now if they can just make a decent cross-platform runtime. Or let me compile it into a binary so I don't have to depend on whatever they've got or send them the whole runtime myself.
Or something like that. I really enjoyed my personal java project, but when I tried to do anything more advanced I just ran into such cross platform garbage that I couldn't see straight. I ended up using OpenGL instead.
I still have some long term hope for Java, though.
Cheers.
Please point me to a source which verifies your claim.
The Internet is full. Go Away!!!
Ok, I'll bite.
C# cannot be faster than Java because it is an evil clone of Java. It will run at the same speed, or even slower.
Thanks for playing fanboy!
Sigh... for the 100th time now:
...).
The JVM features a dynamic compiler; this profiles the application as it runs, then compiles the bytecode to highly optimized native code. It doesn't compile everything to native code when it is first used (as a JIT does), because then it couldn't spend a lot of time optimizing the code (which costs a lot of time).
This means: after a while, you Java app runs as native code, optimized for your particular CPU (no i386 or other stuff; it uses SSE if possible,
murphee
Kernighan/Pike revealed this years ago - the hopelessness of C++ that is.
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
You have no respect for code. Learn assembly and then we'll talk.
They may not have respect for code, but at least they're making stuff. How's that new finance/office/anything real/custom software you're writing in asm coming along?
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;
Tell me I'm not crazy.
https://www.accountkiller.com/removal-requested
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.
The code in the c++ examples is really pretty much the slowest implementation that could have been written. I suspect he used the absolute best java code he could, but used generic c++ code.
Perl/Tk has to be able to work with X Windows, Apple and Microsoft. So it's stuck with the lowest common elements of all the operating systems it can run on.
But wait - Perl/Tk apps suddenly don't look like something someone might pull out of overused public bathroom! They actually look pretty normal, fast and pretty.
I'd say AWT was much more ugly - Swing in comparison looks pretty good
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.
I don't hate java, but the results don't make sense. If the code is implemented in the same manner for processor bound tasks, there is no reason that java would out perform C++. Java isn't fully compiled (it runs on the JVM) and necessarily has extra overhead.
Either the G++ compiler is subpar, Sun just did some optimizations for people who don't know how to code, and/or Java's grabbing more resources and the G++ compiled programs are running at a lower priority.
There is no way that a language that is running through simulated hardware is going to be faster than a program that is running on the hardware it was compiled for.
What? Because I gave Java another chance when it had matured and discovered that it's quite quiick these days?
/. post which is that Java is slow no matter what, or if it's not slow, then its ugly no matter what (ignoring the multiple GUI options like AWT / Swing / SWT or the skinnable options)?
/. I don't care if you want to stick to C/C++ - I use those languages still for somethings (small CLI programs are a good example) I don't care if people stick to what they know, but this endless uninformed bigotry that's displayed on /. is just pathetic.
That makes me a language bigot?
Rather than the typical
Excuse me if I'm not especially polite about it, but I'm sick of hearing this crap from
I'd be interested in comparing the speed of the native code generated by gjc to the that of JVM.
-josh
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:
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.
I actually find Java significantly more painful to develop in because it takes such a huge amount of time to start up the JVM that a debugging session is an exercise in fetching coffee. The class libraries are also poorly designed, and the language is excessively verbose.
Need a Python, C++, Unix, Linux develop
Bloody Good Idea, Mod parent Up!
Seeing things like this:is hurting my eyes.
This page has more information about this horrible malfeature.
________
Entranced by anime since late summer 2001 and loving it ^_^
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.
The Just-In-Time Compiler in the JVM compiles the bytecode down to native code at runtime, so most of the time you're running what's effectively a native executable. Now, since the JITC runs at runtime, it can make optimizations based on the actual behavior of the program (as opposed to normal compilers, which don't have access to that information). That allows more aggressive optimization, effectively means you're running a native executable that's continually being optimized for your system. Pretty nifty.
Now if only Swing wasn't so bloody inefficient....
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.
If I was doing something low-level, I would use C or assembly. If I was developing a large (and perhaps distributed) application, I would use C++ or Java or C#. I would never use C or assembly in these roles so why would I care about comparing them with C++/Java/C#. Of course they're "faster". So what?
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.
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
Java has had a lot of effort put into it over the past four years. It's now a mature platform, with everything that label implies. I'm looking forward to the 1.5 release, and it seems the Java community is more excited by this release than anything since 1.2. .NET, on the other hand, still feels very much like a work-in-progress below the flashy GUI stuff that Microsoft is so good at (and which is perhaps the remaining major weakness in Java[1]). There are some things it gets "right" that Java doesn't, but it's clear that it's a 1.x release. Of course, Microsoft isn't standing still either. The resulting competition is good for both developers and end-users.
[1] The problem is largely due to widespread ignorance concerning best practices for creating a user interface in Swing. In addition, GUI design tools are notoriously poor at generating good-quality code that does use good practices (though this is improving); and books provide simple, small examples suitable only for the toy applications they showcase. Most Swing developers learn the tricks of the trade through experience and code borrowing.
-Thomas
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
A few months ago, I ran some Java code and comapred it to C (not C++, C is way faster) and the result, to my surprise, Java was faster. The functions in both sides were identical, but Java executed faster. I ran this with gcc Sun JVM 1.4 on Java Desktop System 1.0 and RH 9.0. If you don't beleive me, try it out.
Research like this is useful for the propagandist/advocate.
Even though it completely fails to address issues such as startup time, runtime linking cost, and such minor nits as gc and compilation delays, as well as the way all these things interact as applications grow, not to mention as memory use, it does show that Java can do a mean synthetic benchmark -- and lacking pretty much everything else, that's all the propagandists really have.
Most people will (or should) recognize however, that this is a lot like saying, "hash tables are faster than arrays!", without specifying the operation, the hash function, or the data set.
clicky goodness.
________
Entranced by anime since late summer 2001 and loving it ^_^
Since when is 33 less than 25?
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!!!
Great website for any Java programmer. Has helped me quite a bit.
Based on upvotes, Ageism is the only "-ism" Slashdotters care about and think isn't SJW
one out of two ain't bad....
You know not of what you speak. Try using C++ streams vs. write() on a fast disk - something like a SAN.
See the write()'s move data a 200+ megabytes/sec. See the C++ streams struggle to break 2 megabytes/sec.
"The C++ version would have taken longer to write and debug."
Right on.
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.
In my two decades of experience, even multi-million dollar engineering apps still don't understand the concept of WINDOW RESIZING!!!
I wish all Unix GUIs were done in Java.
https://www.accountkiller.com/removal-requested
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.
You can skin it as long as you like it will still not be native and not look native.
You will not be able to get windows cleartype or X11 anti aliasing font smoothing in a swing app.
Sun needs to embrace SWT or make something better ( thats not hard ) but whatever they declare for standard has to honor the platforms native appearance, there is no other way.
P.S: yes i have seen beautiful swing apps, yet they look out of place.
Hear me out. At my school, there's a project in collaboration with the US Dept of Defense to make a hardware compiler for Java. This is because the government likes using Java for its ability to run on so many platforms, but they also want it to be faster if it's running some critical system in aircraft.
Though a hardware implementation would be cool, i doubt it'd make a large impact in the civilian sector, due to cost.
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.
HIV Crosses Species Barrier... into Muppets
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:
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!!!!
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!
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!
This may be a little off topic, but why are linux programs primarily compiled with gcc? I've read how people complain how linux seems slower than windows. I've read people talk about how slow gcc is? I myself feel linux is slower than windows based on using windows and linux on the same computer. I use linux on my laptop and it's has a decent cpu so it doesn't seem to lag much, but the slowness is pretty bad on older hardware. So is gcc to blame and if so, is it possible for me to switch compilers and still run emerge on gentoo like I'm used to?
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).
Offtopic? Please read the first line again.
Finest word processor ever.
If it feels slow, it IS slow....
Sorry, but I'm not taking the results of someone who looks like they learned everything they know about c++ from reading the comics in "C++ for Dummies" very seriously. Get a real c++ coder in there who doesn't do stupid, wasteful things with pointers and then maybe there can be a decent comparison.
In other news, I can write a program in assembly that performs much worse than VBScript if I put my mind to it and make a bunch of stupid assembler mistakes.
Finkployd
... John Carmack has updated his .plan with details about his next engine, codenamed "Mammoth".
The engine features real-time raytracing and is written entirely in Macromedia Flash, which provides a level of performance superior to that of OpenGL.
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.
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
gcc doesn't exactly produce the most optimized code - guess he didn't know about that. Oh well - just another java freak trying to justify his poor coding skills. :P
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.
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.
Pocket PC Games
It's a much better idea to write a compiler in Java than in C. Compiler performance doesn't matter that much, but correctness does matter, and it's easier to write correct code in a clear object-oriented language like Java than C.
I didn't RTFM, but from the headline, it seems like the word CAN is the gotcha, any language that has a purpose for existing can be faster than any other languages in certain situations. This is because computers are (generally) better at optomizing code than people.
But, if this guy is saying that in general Java is faster than C++, I call bullshit. Don't get me wrong, I love Java, and there are a lot of great things about it, but speed ain't one of them.
With the power of modern computers, java is generally fast enough, but if I'm writing an application to run on my 200mz ram hungry and already overloaded server, then Java is not going to be my langauge of choice.
I wish people would just get over this programming language pissing contest that seems to have been going on, and promote each language based on it's own merits, and not try to say that any given language is the end all be all of programming.
In my experience, Java is fast to write, and C++ is fast to run. C++ can be hard to debug, and Java can make it hard to eliminate overhead.
If one day Java is faster than C++, Then I think it will have come at the expence at many of the things that java gets right.
Famous Last Words: "hmm...wikipedia says it's edible"
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
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.
Wow, who'da thunk it? I just gave some of his stuff a test run, and it looks like he's right. The JVM stuff is nearing 2x the speed of my G++3.3.3 stuff on some tests. I would like to see it tried with 3.4.1 or even the new 3.5 stuff, if possible. Anybody else do at home comparisons?
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.
I must say that there is simply no way Java could be used for serious computer vision work, where I specialize.
The need for speed is too great. Lack of memory-management optimization is the killer.
Having programmed in Java for years, it was painful to give it up and switch back to C++ for performance reasons. Also, Intel's openCV library and other such C/C++ libraries are very useful.
Also, in terms of ease of development (rather than speed), MATLAB has JAVA beat without question. I mean, if you are going with a VM, why not go all the way with an interpreter?
I know of at least 3 companies that do heavy work in vision. Each have around 20 guys doing research in MATLAB and at least a dozen to translate it to C++ or C# to get it to run in real time.
Robo-Blogs of the world: UNITE!
This didn't exactly fill me with optimism either:
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."My life's work has been to prompt others... and be forgotten." --Cyrano de Bergerac
... and always will be.
Give me ONE good reason what java actually does right?
You need one hell of a machine to run all the crap. It is still not fault tolerant to any degree.
And seeing as it was initialy designed to run video recorders and washing machines, et al, why doesn't it now?
Nick
The JITC uses profiling imformation from the app as it's running to make certain optimizations. That info's not available at build time, so the optimizations can't be made.
The JITC process is generally 5% of overall runtime anyway, so it won't make much difference to the user.
Might be nice if the JITC would save the optimizations it did make for subsequent runs, though.
Honestly, the guy has no clue what he is doing, the numbers are completely meaningless. I mean here is my review with just as much scientific integrity:
:). And anyway, commonly used code is converted to native code if they are called often enough so other parts are mute aswell.
Test Results
------------
Java: 30 GigaQuads
C++: 3000000000000000000 GigaQuads
Sumary
-------
Java: sux balls
C++: is god
I digress, back to reality now.
None of the tests used any form of GUI testing, this is what the end user will mosty be dealing with so here it is, Swing is crap, its slow, ugly, and just a bad hack job. Eclips (the main opensource IDE) uses SWT instead of Swing to avoid these problems, for the uniformed, SWT simply does C calls to the OS to display the os's GUI library (this of course is at the expense of cross platform compatability).
When it comes down to it a JIT compilere has the advantage of being able to optimize for memory size and what not, but then again JET compilers can spend all the time they want getting the code tweaked just right so its neither here nor there, even though experience has shown that the later tends to be faster as the system specs are generaly too similar nowdays (Umm try running java on a 16Mb machine
In summary, JIT will always be a bit slowere because of the initial overheard, as for Swing, well thanks Sun you can have that pile of steaming shit back.
GPLv2: I want my rights, I want my phone call! DRM: What use is a phone call, if you are unable to speak?
I hate to attack you personally, but maybe you should think about a career outside of CS. Well-optimized C++ with *properly* written code HAS to run at least as fast or faster than any JVM. I've worked in the game industry for years and know what happens at the machine language level. In the end everything is machine code. The only way Java can run faster is if the C++ optimizer isn't doing its job (doubtful) or if the C++ code does stupid things (likely with CS students like you writing it).
Have you ever tried Qt?
> 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.
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.
Bwhahahahaha .ahahashah haah a .. .. there's more..
.. who is the fucking moron that has obviously used neither language!!???
oh wait
BWhahahahahahahaha -gaha hahahaha
In response to what many of you have and will write:
.class to native code you really have native code directly executing.
-- 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
-- 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.
Quite rediculous-- the benchmarks do /not/ compare apples-to-apples at all.
/really/ want to argue (I think wrongly) that since Java's got a built in hash type it should be used, at least then also compare a good STL map impelmentation.
For one example, compare the Hash benchmarks. The C++ implementation uses a homegrown data structure, and algorithm, while the Java version uses a no doubt highly-optimized built in version.
To be accurate, the benchmark needs to use explicit data structures and algorithms completely implemented in both languages.
If you
Additionally, although many of them are good, a number of the benchmarks for C and C++ at the Great Language Shootout can be improved (some easily, some with more work) with respect to their implementations. (One would assume that's probably true for other languages as well.)
Anyhow, to compare A to B properly one must be measuring the same thing with the same units. The benchmarks presented here don't convince me that they do that.
april fools day already? ... No.. ok well what's going on here?
:|
some sort of alternate universe i must have fallen into...
-judging another only defines yourself
Well, you'd better tell your mom to switch perfumes.
Well.. maybe. Or Maybe not. But Definitely not sort of.
When you get out in the real world and begin working on real projects, you begin to notice when you are writing embedded code v. when you are writing an IDE. There is a time for C and a time for Java. Speaking from the real world, we use C for the embedded code and Java for the IDE. We don't even use assembly for embedded apps. When you are working with customers, deadlines, and cash, you too will stop caring about silly things like "respect for code".
Sun needs to embrace SWT or make something better ( thats not hard )
Cool!! Where's the web page for your implementation?
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
The performance gain won't be as much as you would hope - remember your class files may change in between different invocation of the JVM, therefore checks will needs to be made to make sure those code segments are still valid - and that may be more work then it is worth.
'no one should ever run the client JVM when given the choice,'
What choices are there?
John Kerry is a Joke!
As others have pointed out here, it's easy to write a program in your favourite language (in which you're an expert) and then translate it badly into C. No surprise about the resulting benchmarks.
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.
I just did my own benchmarks for Ocaml, C++ (with O3, march, ftracer), and Java with the code for matrix, ackermann, and heapsort.
In all 3, Ocaml came out fastest on my machine.
Results:
Matrix: G++ - 2.467s
Java - 2.462s
Ocaml - 1.062s
Ackermann: G++ - 2.147s
Java - 1.023s
Ocaml - 0.603s
Heapsort: G++ - 1.266s
Java - 1.327s
Ocaml - 1.116s
(Note: the argument to heapsort was 1000000 and to
ackerman was 11)
I'm a wee bit surprised by this, but not much.
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
c++ is almost twice as quick. Running his code!
./methcall 1000000000 ./methcall 1000000000
cslin185% g++ methcall.cpp -o methcall
cslin185% time
true
false
31.640u 0.000s 0:31.63 100.0% 0+0k 0+0io 200pf+0w
cslin185% javac methcall.java
cslin185% time java methcall 1000000000
true
false
31.420u 0.000s 0:31.46 99.8% 0+0k 0+0io 1384pf+0w
cslin185% g++ -O3 methcall.cpp -o methcall
cslin185% time
true
false
17.710u 0.000s 0:17.71 100.0% 0+0k 0+0io 199pf+0w
I believe this is what FX!32 used to do for running Win32 code on Alphas. Came out in the mid 90s IIRC.
dmd
use the java to C# then test java, c++ and C# side by side.
.NET already has this feature (so it does work for C#) You use a utility called ngen.exe to generate a native image which is then cached in the Global Assembly Cache.
"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." Go in with a slanted view, return with slanted results. Making Stuff Seem Like It Is Better Than It Really Is 101.
Caching the native machine code would compromise the security of the bytecode verification that happens when a class is loaded and before it is just-in-time compiled. The cached code could be edited in binary form to do malicious things.
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.
anything else?
Yeah, Kuro5hin is better than Slashdot.
In the real world, the developer would have run the profiler several times on his program and optimised it. Now we see Java for what it is - a tool to push the cost of what is normally development work onto the end user...
The last time I benchmarked Java vs. C++ myself, C++ came out on top overall but it was fairly close. However, that was using Java compiled to a native executable, no JVM was involved.
Being primarily a C++ programmer I may be a little biased, but I can't see Java ever being faster than C++ and definately not JVM executed Java. Oh, don't get my started on C, in my own benchmarks Java got its ass whooped that's all I'm gonna say.
I personally like both C++ and Java as tools, who cares which is faster? They both get the job done. *shrugs* Can't we all just get along?!
This is another case of a java fan skewing the statistics in javas favor. Of course by not using full optimization settings in the C++ compiler you can generate slower code than java.
The fact is, if you know enough about how your C++ compiler compiles your C++ code you can make decisions about coding style that will ALWAYS produce faster code than java. Any JVM/JIT still doesn't know as well as the programmer what the app is trying to DO, and therefore cannot hope to achieve the level of optimization available to a human brain, except in some contrived cases where approximately equal performance can be achieved.
REMEMBER: That JVM/JIT was written in C++ or some other similar pre-compiled HUMAN BRAIN optimized language no doubt. I can always drop into asm{} if i need that extra boost in my C++ app.. How can I do this in Java? Can't we all agree java is a great language and not get hung up on the FACT that it trades flexibility for speed, or trying to confuse the issue with meaningless statistics?
It pisses me off that the java attitude seems to be that The Java Engineers have made a language that is so superior that you the programmer couldn't hope to make anything more optimal than what the JIT spits out.
Also.. How can a JIT compile code fast enough to be Just In Time, but yet magically optimize the crap out of the code better than Intels C++ compiler churning through source files slowly one at a time and doing extensive analysis of how your algos work but doing it on the programmers workstation, instead of on somebodys 486 based webbrowser?... (thats Intel the CHIP MAKER who makes the CHIP that JVM is running on mind you.)
The sad answer is IT CAN'T.
Java is flexible for some applications and C/C++ is FASTER and sometimes less flexible for others. Get over it. Now once we get widespread adoption of native Java CPUs things may be different.. but until then, i'll keep lookin at the assembly when I want to be sure of what my code is doing on an x86.
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.
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!!!
Ok, so I'll admit that I'm a C++ programmer and I don't know Java. I have a question. If all this profiling can make Java faster than C++ over the course of a few runs of the application, why can't a developer do all the profiling before hand, and then ship the cached code that was translated to machine code by the JVM as a native binary? Wouldn't you then have an app that doesn't require a JVM and would be faster than the C++ version?
LS
There is a fine line between being a cultivated citizen and being someone else's crop. - A. J. Patrick Liszkie
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.
Jackasses who start a conversation with "Ummm..." should be SHOT.
Just because Athena/Xlib sucks doesn't mean AWT and Swing don't suck. If you want a toolkit for C++, then both WxWindows and Qt are wonderfully modern toolkits that are easy to write for. If you want Java toolkits, hopefully you skip AWT and Swing and target IBM's SWT instead. GUI toolkit is a really poor reason to choose Java. Choosing Java because you want the protection from buffer overflows, pointer corruption, and other common C programming mistakes is a good reason.
I used up all my sick days, so I'm calling in dead.
I've heard that studies indicate that programmers who write their code in Java are 2 to 10 times more productive than those who use C/C++, but I can't find pointers to those studies right now. Anybody got some references?
I any case, I think it's probably true, speaking from firsthand experience. I programmed for more than 15 years in C/C++, and now that I use Java, I pray daily that I'll never have to write another line of code in C/C++. With Java, things often work the first try and just don't break. With C/C++, I've found that latent bugs can lurk in the code for years before they're tracked down and fixed.
Of coures it is possible to write good code (or bad code) in any language. But clearly, with Java, it's a lot easier to write good code. Java is much simpler than C++, and much less dangerous than C.
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.
-
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.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
Couple of apps that we converted from C++ to Java are MUCH faster in Java version. Some design changes undoubtedly have contributed to the increased performance but Java being fast also helped.
Actually, no. Show me the Perl/Tk app that looks normal, fast & pretty on OS X.
Not quite true. Look at the branch prediction instructions in RISC architectures. They pretty much allow the instruction pipeline to ignore the 'loop if test isn't met' instruction.
-s
the java is a nice little tool for bad coders, who have difficulties with the concept of pointer
I also found that it's prefered by a greater percentage of women, but it should be verified.
Comments ?
Looking at the benchmark code, the C++ code uses the STL extensively. The STL is slow and bloated. The standard Java class libraries are much better designed and written and I'm not surprised with a good JIT compiler, java beats the STL for speed.
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
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.
you are right of course. i just hate themes and must say so at every available opportunity. i have nightmares about living in a world where every single piece of software on my computer can have a theme applied to it. hold me.
That's a good point though I somehow imagine that's not quite what the poster has in mind. It's not exactly a mind-blowing demonstration of graphical prowess, even if it was a great game...
"There is more worth loving than we have strength to love." - Brian Jay Stanley
C# sucks, but java rocks? Gee, your bias doesn't show much. They're almost exactly the fucking same.
Oh, no, I forgot... C# is a Microsoft technology - that makes it worse.
I believe the inferrence was that Sun could hardly create something worse than Swing, not that the poster him/herself finds the task of creating a UI toolkit implementation to be "not hard".
I strongly advise acquiring the ability to read.
Didn't the reimen hypothesis prove this ? Or did I miss any thing in that apology ?
for the last time people, I am "frodo from middle eaRTH", not "middle eaST".
However, the new guy gets:
Somehow this new guy's tests conclude that Java is 10x faster than C++ in the exact same test? I call shenanigans.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
Unfortunately, SWT is a pig these days. Like I said, it's terrible to code for and since Swing is actually faster than GTK+ now, there isn't much reason to use SWT.
Show me a developer who use both SWT and Swing who still prefers to use SWT. If they exist, they are very rare.
Oh, and of you really want to use the GTK+ widgets in Java, there's a much better project, the JavaGNOME project.
You believe everything Intel tells you?? It's not free, becuase it's another thread banging on your memory (esp L2).
And even if it was "free" there is still an opportunity cost - some other thread (not your program's) could be running as well.
But Qt ain't free. ;-)
(unless there's a freeware/OSF version??)
https://www.accountkiller.com/removal-requested
I can agree that there are some stupidities in the class libraries, but there are no standard class libraries for any language that even comes close.
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
They are slow, they leak memory, they crash.
Yeah, go ahead, blame the JVM.
Sure, it is nice to get apps under Linux that would otherwise be Windows only... But it is far from ideal.
Sorry, but as a user I dread java apps.
Then cache it where only root and/or the special java user can edit it. Practically it isn't a problem if each user keeps his own cache since it will have to pass through the bytecode verified to get to the cache and if the user wants to scribble on his own files, he doesn't have to gets so complicated as to dork with his java cache, he could just type "rm -rf ~" and be done with it.
"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."
Sorry but when you use 4 engineers for 6 months you can't claim no to little effort.
what?
Funkitup's benchmark agrees with the original site's results (and substantially discredits the new guy). See my post calling shenanigans on the new guy.
No, the worst thing about Java, IMHO, is classpath hell.
It's comparing a language using a static compiler
to a language using run-time compiler. How is comparing two different types of compilers going to provide a useful comparison of languages? Until I see a study of JAVA on a JVM compared with C/C++ on a comparable run-time compiler I think these benchmarks are pointless. I thought engineering was about design and choosing the right tools for the job, not learning a single tool and shouting "It's the Best For All Your Needs!".
As a side note, from TFA:
"The results he got were that Java is significantly faster than optimized C++ in many cases."
That says many cases, not a majority of cases and damn well not all cases. OH NO! A newer language has advantages in certain cases! "I think I'm going to have a heart attack and DIE from that surprise!"
-- "Someone's gotta go back for a shit-load of dimes."
Uh, Java methods are virtual by default.
The better jits (e.g. HotSpot server) can inline virtual methods at runtime, but that's a fair optimization. No static C++ compiler can inline virtual methods.
c# has fucking xml gobbledegook interspersed with C++/Java style code. C# has NO CHECKED EXCEPTIONS (this alone meant it was discounted in my employer's enterprise business boring-as-hell-but-vital apps). Java and C# are going for the 21st-century-COBOL market, and Java is a better COBOL than C#.
I can understand someone thinking Java was better than C# despite their broad similarities.
The matrix multiplication was implemented very poorly in C++. First, the matrices are constructed as arrays of pointers (to facilitate passing between functions--C++ is bad at this, modern fortran is *way* better). Then, the inner loop of the multiplication is
for (k=0; k<cols; k++) {
val += m1[i][k] * m2[k][j];
}
so that a different pointer must be dereferenced each time m2[k][j] is accessed. In short, transposing m2 first (an O(n^2) operation) would dramatically improve performance.
The poor chap is obviously intellectually challenged if he can't debug some C or understand the gcc errors. The comment I find most amusing is this: "The test was creating a new StringBuffer in each iteration of the loop .... I updated the code to use a single StringBuffer and appending to it inside the loop."
Modern Java JITs (2001 onwards) optimize this particular bottleneck and best programming practises recommend you minimise variable scope as much as possible, that means declaring it in the loop. Sure the original Java runtime environments (pre hotspot) would redeclare the string buffer in every iteration but not in Java 2! I did have an article on this but I can't find it so please make do with this and this.
I think we can safely ignore his results until we have a real professional with an actual degree look this over.
I'm sorry but there is
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.
In theory, optomising C++ compilers is done for processors, whereas JAVA optimisations are done at the OS level. Makes sense to me then that JAVA would be faster with the amount of effort put into it to make it run faster.
Not since Marie-Antoinette played milkmaid has looking simple and honest been so fake and complicated.
it could be faster and i've read a few articles that show how. Others have done similar testing too I'll be pleased to see java implemented but I still love perl and a bit of gawk. see lots of here language benchmarks - I really like this site.
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.
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.
I recently read a PhD dissertation discussing (among others) a java-based grid environment. At first the entire idea sounded odd to me because of an expected performance drop. However, cases where java can be as fast as and sometimes even faster than optimized C have been shown before.
In the dissertation, two papers are mentioned that compare java to C and apparently show positive results for java. I haven't actually read these papers, by the way. However, their titles suggest that they might be on-topic here.
The first is "Benchmarking Java against C and Fortran for Scientific Applications" by J. M. Bull, L. A. Smith, L. Pottage and R. Freeman
Second, and judging from its title perhaps less on-topic is "High-Performance Java Codes for Computational Fluid Dynamics" by Christopher Riley, Siddhartha Chatterjee and Rupak Biswas
finally, the dissertation can be found on Rob van Nieuwpoort's publication list and is titled "Efficient Java-Centric Grid-Computing"
As citeseer is always crawling, even without a link on slashdot, I was afraid to post this... but then I remembered that noone here actually reads the FM :) Jokes aside, it is a great resource and I hope that they get some mirrors soon.
I find it disingenous that the story does not mention the C++ compiler that Java was compared against (nor the Java compiler).
C++ has some really poor implementations. For example, in Kernighan and Pike's "The Practice of Programming", C++ comes out slower than Perl for their application.
The non-story here might be: Really Good Java Compiler Beats Really Bad C++ Compiler.
----
Notes on Stuff
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?
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"
WxWindows is called WxWidgets nowadays. wx4j is a binding of WxWidgets for Java, and is similar to SWT. Still in first stages of development, though.
You must be new here. Ever used a TCL app? Or any native Unix app that uses Athena widgets? Or even just plain Motif?
Here's a game who's graphics will blow you away and settle this once and for all, Java can be used when performance is REALLY needed. BEHOLD! The ultimate 3D java MMORPG game, Runescape! Screenshots here.
:P
"There is no spoon." - The Matrix
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.
Always keep a sapphire in your mind
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..."
this
Azureus is a good example of the only Java application that I use regularly (aside from Eclipse). And it is also based on SWT. I don't care what the acronym is supposed to stand for, I say SWT is short for 'sweeeeet'.
Why does the example use a recursive fibonnaci sequence algorithm? It's so slow, and the runtime is dominated by the function call time.
./fib_recurse 40
./fib_for_loop 40
For example:
[bdr@arthurdent tests]$ time
165580141
real 0m3.709s
user 0m3.608s
sys 0m0.005s
time
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.
That line made my blood curdle. Of all the UNIX apps I've used, the ones that were written in Java are my least favorite and least used apps. I prefer apps written in C with a toolkit like Qt or Gtk+. Both of those are exceptionally fast and modern looking. Toolkits like WxWindows compile natively with no extra dynamic libraries required and are crossplatform.
But as anyone really using *NIX knows (yes I'm talking about you gentoo, sourcemage, LFS and slackware guys), you always pick the app written in C before the app linked against libstdc++. It may sound elitist but it just seems that people writing in C know what they're doing and take the time to write more solid code. Not to say you can't write a crapwagon C program, perhaps its just easier to fuck it up when you're writing C++.
To go back to your line that made me choke, "I wish all Unix GUIs were done in Java." Perhaps large one-off or custom design software could benefit from Java. But I think this is the minority not the rule. The apps I use on a daily basis are the window manager, xterms, media players, web browsers, document viewing/creation apps, etc. These types of apps have matured over the last 10 years and are all (the ones I use at least) written in C. That is why I can use X and actually do work with no problems on my P133 laptop. Compare that to OpenOffice, Limewire, etc al that I would not touch with a 10' pole for fear of my laptop shutting itself quickly and breaking off my fingers in retaliation.
Well duh. He didn't run it on Gentoo.
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
If you want speed, for God's sake, write it in C! Oh, another C vs C++ bigot. C, being largely a subset of C++ with a few minor syntactic exceptions is not going to be faster than C++ since you could just write a C program anyway. Now that that is out of the way, C++ allows you to write fast code more easily, by providing templates. Sure, templates have some warts (thought I have no idea what you're talking about code being "unwoven", desplite having done planty of template programming), but it's generally easier than doing the equivalent with macros. Yes, it is possible to write slow code in C++, maybe it is easier than in C, if you have not much clue as to what you are doing, but it is precisely as easy to write fast code in C++ as it is in C, since C++ is a superset of C.
SJW n. One who posts facts.
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
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
Qt/X11 Free Edition
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
I started writing assembly in the early eighties as a kid. At the time, it was the right tool for the job. RAM and storage were a premium.
Today, I code in Java and C++. Why, productivity. I've found Java to be one of the most productive languages I've seen (C# may have caught up).
If I were writing code for micro-controllers, then I'd still be writing assembly because it would be appropriate. Writing complex business applications deployed on large clusters of servers would be insane to do in assembly.
To give you credit. I do notice that developers with a strong assembly background write much better Java and C++. Perhaps because they understand what the machine is doing. They know how to use javap to disassemble class files to see what the compiler is creating.
To take credit away. Most projects need the balance of speed and speed of develpment. Usually this is a trade-off between C (speed) to Java (rapid dev). The article suggests that the speed sacrifices are much less than they used to be.
----- If communism is a system where the government owns business, what do you call a system where business owns govern
The point is that this test was obviously created to exploit the fact that java uses jits. This would be ok if there were a test specifically designed to exploit every little advantage C++ has over java, but there doesn't seem to be.
(/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.
There seems to be very much bragging on both sides - "You could have used optimizer x, written better code, etc".
It seems that to get accurate results which language is actually faster, we should start a contest where programmers can defend their favourite language as much as they want, and do all the optimizing they can possibly squeeze out of the language.
There could be just some different problems to solve or things to do with the program, and the thing should be done exactly the way as described by the contest starter.
After a while, when all the contestants have submitted their code, and it has been tested by the contest jury, we would have a quite clear winner, at least for the few problems presented in the contest?
So, all we need now is someone willing to get some reputation from arranging a contest like that. =)
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):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
Information: "I want to be anthropomorphized"
It must be a wonderful discussion, because as pointed out by Nathan himself: It's a safe place to rant without being contradicted by apologists, toadies, people worried about their unwise career choices, or even facts.
Okay, Swing is the SECOND ugliest widget toolkit.
Well that depends on if you wrote the error messages. I could barely make it through your post, what with the extra characters and all.
But then you don't get the cross-platform goodness of having only one binary to distribute. (Although most Java apps I've seen don't have that much anyway.)
Why stop at -O2 and not use -O3 for g++?
Most users use 1 platform, and expect an app to look like and behave consistently with other apps on that platform.
"
"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."
Sorry but when you use 4 engineers for 6 months you can't claim no to little effort.
"
He didn't say "no to little effort". He said NO WAY with AS LITTLE effort. The original poster believes that it took less time because of his choice of language.
I'd say it was the proper design up front, but that's me. I'd guess that the original imaging app was a hack, held together with chewing gum and bailing wire by their description. The new app has an actual design.
Language choice? Pretty much a wash. It boils down more to APIs than keywords, in my experience. He who has the easiest architechture wins the "ease of implementation" award, regardless of how you define a loop or how you terminate a line.
Fooz Meister
even if java is a few seconds faster, it doesn't matter, its the same concept of "our computer is 2 seconds faster, pay us an extra 100$ and be faster by 2 seconds", only, learn our language, and be faster. A lot of it is the methods used, and even if you used the fastest method for whatever your doing, it doesn't matter if it is faster by a few seconds. I dont think any of us should choose what programming language we use by speed tests, its what the programmer feels most comfortable using.
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: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
Like Java, C# is compiled to an intermediate code for a "virtual machine" that is typically JIT compiled for the target processor. I've been amazed at the speed. I'm doing graphics applications where I'm moving bits around manually, and C# is plenty fast! And it's nice to have garbage collection and modern features.
C# also has some other advantages over Java: it's a standard language (it has been submitted to the ECMA standardization committee), and has advanced features like "generic types" (similar to templates), pointers, and good XML serialization support.
Best Buy can have you arrested
Don't forget that binary x86 instructions are also bytecodes. This means that you could get the benefits of dynamic recompilation by running an X86VM on your x86 machine and could program in any language you want. In fact modern x86 processors already do something like this in hardware as they translate opcodes into micro-ops.
Though it does seem rather odd for the "future" of programming to be writing code to feed to an optimizor/translator which feeds code to an optimized translator which feeds code to the real processor.
in some tests. And C++ is faster in others. So what? If you select development platform solely on speed, you're making a big mistake.
This would be an interesting one wouln't it...
Isn't this more or less the point of GCJ?
GCC 3.4 has a new parser, no longer based on yacc.
GCC 3.4, also has a new framework for optimization -- gimple and generic.
He is running, technically, and outdated toolchain. A new test should be performed with glibc compiled with GCC 3.4, and GCC 3.4.
gcc.gnu.org
He said the original program took 12 man years, and the new one took 2 man years and is a much better application.
Definetly little effort relatively speaking.
"If they have both, tell them we use Linux. And if they have that, tell them the computers are down." -Dave Chapelle
Why not? Give a reason.
BTW templates error messages stink, at least in GCC and Visual C++.
"I think this line is mostly filler"
Of course I didn't RTFA, but as long as it's apples-to-apples it shouldn't be a problem.
Check out Michael Abrash's Zen of [Assembly|Graphics], one of those... It has a chapter on optimization involving recursive versus non-recursive functions. He implements, IIRC, a BSP-traversal algo both recursively and non-recursively, and shows that without optimizations they are quite different, but when fully optimized (in the compiler) their performance is nearly identical.
Those are likely coming from his Linux box.
Windows does not enable smart quotes for edit boxes, except when they are pasted directly into the box. There is no automatic handling of quotes in Windows controls, unlike Linux which tries to outthink the user at every step.
What if I were to tell you I use mozilla? You would have looked a lot smarter if you had told me to "select HTML Formatted" before making a post or even preview your post before pressing the submit button.
-----
One is born into aristocracy, but mediocrity can only be achieved through hard work.
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....
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
Who doesn't like free music?
I'm posting this so that you (the moderator) have some context to consider twitter and not mod him up whenever he posts his filler preformatted rants about installing Knoppix or whatever that unfortunately get him karma every single time and allow him to continue posting his trademark toxic crap (read on) day in and day out. You may consider this a troll - I consider it community service. And I ain't kidding.
If you're a /. subscriber, I invite you to look through some of his posting history. I guarantee that you'll be hard pressed to find someone that is more "out there" than twitter. You'll also probably notice he's got quite an AC following. Don't just read his posts, make sure you go through the replies.
To get an idea of what I'm talking about, check this post out. I mean, this is an article about email disclaimers, right? The parent of the post is complaining about the ads in the linked page and so on, and twitter actually goes off on a rant to blame it on Microsoft and recommend Lynx. WTF?
Here's another. In this post twitter not only calls the OP a troll but attempts to "tell it like it is" while making some vague argument about "GNU". Yes, if you're confused, you're not alone. The reply (modded +4) proceeds to simply destroy his bogus argument. You will notice he did not reply. This is what some people call "drive-by advocacy". A sort of I'll just leave you with my thoughts here and move on to the next flamebait kind of deal. In fact, he almost never replies because he knows that his fanatical arguments simply do not hold up to any sort of discussion. It's not that he's chosen the wrong cause - he's just going at it in a completely wrong way.
More? Just read though this post and the subsequent replies. I guess this stands on its own.
More? Bad spelling in astounding conspiracy theories, more offtopic FUD and uninformed "I'm right, look at me" rants, promptly proven wrong. Worse even, twitter wants to be RMS, apparently (that first one is a winner). I mean, really. You think?
FUD, FUD, FUD, FUD, offtopic FUD
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.
Actually, /. doesn't like a whole lot of standard HTML formatting, so it would have spit up those codes anyway.
The best solution is to just stay away from smart quotes altogether.
These results clearly show that Java is in the same league as C++, despite being slowed down by running in a C-based operating system. Just imagine how fast is would be if the OS was not so archaic.
A safe, object-oriented operating system would make Java way faster than C++:
and there are probably many more advantages. Take a system like that and run a C++ app on it (in a CVM) and you'll see it run orders of magnitude slower at best. C/C++ is just a much slower language than Java.
And Perl is faster than Java.
;)
And cows can fly.
But seriously, Perl is faster than Java.
Just roffel Ma friend!
Why not just use VB? It would have been the easiest and probably faster.
By "optimizing" it you are circumventing the test, moron. Why don't you further "optimize" it and just print out the result?
I thought this was /., where's the:
"Linux beats Window$?"
and don't forget that "$"!
amd kills intel
C# murders Java
NT annihilates unix
ascii obliterates ebsdic
XML belittles html
Mac redefines Windows
SCSI uber alles
bash trumps ksh
csh cracks bash
sv strangles bsd
aix jack-boots sv
and lets not forget:
vt100 reins supreme over all other user interfaces that have been or ever will be invented!
There is no excuse for writing anything in C++ in this day and age:
- If you are writing a kernel or an embedded bit whacker or a real-time thing, use C. C++ is too slow.
- If you are writing an application, be it desktop, server, whatever, use Java or C#. C++ is far too unsafe.
- If you are writing a rapid prototype, use PERL, or Python, or Ruby.
My condolances to the KDE kommunity. It's a cool desktop & all (I'm typing on it) but bolting your whole framework on a C++ basis was a really unfortunate choice. It dooms KDE to long-term security vulnerabilities.Crispin
----
Crispin Cowan, Ph.D.
CTO, Immunix Inc.
But this is beside the point. To run benchmarks well a person must be diligent, methodical, and objective. Being a hacker is not a prerequisite. These benchmarks look a lot better than many I've seen. They might turn out to be flawed, but not for the reason you mention.
Am I part of the core demographic for Swedish Fish?
So, I'm done with my CS degree from RPI, and I'd like to point out we're not all morons like this kid apparently is. Also remember he's just finished his sophomore year, and has probably just taken basic classes like Data Structures and Algorithms and Operating Systems.
It just cheapens my degree, sadly.
--
lds
The fibonacci benchmark IS measuring function call overhead, Einsteins.
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.
_
\\/ are accustomed' - First Lensman
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.
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
Assembly most certanly is graceful and elegant, used in the right hands. And if modern API's and architectures were designed for Assembly in mind, it would be the right tool for many jobs. But the fact is that isnt for a majority of cases.
But try telling me Java is the proper language for a Z80 and I'd laugh in your face. I'd go as far to say C or C++ isn't even well suited in this case.
You can reuse and mantain assembly with the same techniques you do with C or Java. You can also program less gracefully or elagantly.
Well the jerk store called, and there out of you!
Well.. maybe. Or Maybe not. But Definitely not sort of.
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.
Oh GAWD WHY! Why would you compare java to a piece of garbage like GCC??
Even C# is faster than Java. IN fact, MS states C# is faster than MFC
You don't know the POWER of the dark side.
Both VI and EMACS will let you change characters in a file.
EMACS will also let you browse the web, read netnews, ftp down files, read email, run arbitrary elisp software (eval-print-last-sexp in lisp-interaction mode), spell-check, font-lock, run your makefile, interactive-debug via gdb, etc.
Anyone know if there's any truth to the rumor that somebody complained to RMS how wrong it was that emacs took up more memory than his kernel, thereby leading to the creation of the HURD project?
EMACS
= Editing Macros (old)
= Escape Meta Alt Control Shift (new)
double gold = (1.0 + sqrt(5)) / 2.0;
int fibonacci(int n)
{
return floor(gold * n);
}
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.
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.
And the correct name is "GNU/Emacs"!
Some emulation systems have used persistent, offline translation. For example, FX!32 (I think I have the bang in the right place) enabled running x86 Windows binaries on Alphas through a combination of interpretation and static (off-line) translation. Frequently-executed parts of the program would get translated to Alpha code and saved to disk.
One of the main arguments against going to disk is that generating a dumb translation is often as fast as or faster than finding an existing translation and paging it in from disk.
For a long-running application, saving to disk doesn't help a whole lot, since you eventually get an optimized version of everything important anyway. And if your application runs quickly enough that startup time matters, it's probably fast enough already.
at least if you already know C.
The language of the week is Assembly language...
From excellent karma to terible karma with a single +5 funny post...
you mentioned a fact where *everybody* agrees.
Utterly false!
Java has 2 big advantages over C++
Even garbage collection is an advantage rather than a disadvantage, because while C++ needs to free up every little allocation one-at-a-time; a garbage-collected heap can do many-at-a-time.
The only reason Java is slower than C++ is that C++ compilers are more mature.
I find Java's container libraries to be annoying and obtuse. I prefer the STL or Python's containers.
Java's containers lacked an iterator concept until recently, which made it hard to have code that went through a random container independent of its type. And Java's lack of support for generic programming makes use of their containers very cast heavy.
The standard UI library, Swing, is too slow to be used for actual real work. And they stopped bothering with the X event model in Java 1.3, so it's impossible to run Swing applications in a remote X session with any speed at all. Every twitch of your mouse results in a flood of network packets to the Java application, which it then has to carefully process.
Need a Python, C++, Unix, Linux develop
no one should ever run the client JVM when given the choice
That's a pretty damned big caveat when you think about it. I can hear the excuses now... "Of course it seems like Java is slower than C++, you're running it on the client! Duh!"
Don't blame me, I didn't vote for either of them!
This is not going to be the most specific post in the world because I don't have the original source nearby, but...
.NET framework, the difference in performance from one programming language to another is negligable at best. Hopefully, someone else out there read the magazine and can elaborate on his statements, but I think it's an interesting point nonetheless.
In the most recent issue of Maximum PC, an experienced programmer wrote in to defend a recent tutorial on how to program in Visual Basic. He said that with the emergence of the
I use Java everyday at work- its my job. But at home I use C/C++ because it loads quickly and executes quickly.
Java has its uses, but the problem is that Java isn't platform specific. IE: its intended to be bytecode and yes, you may have some program that compiles java into native code and it executes very fast. But your user must run JVM X version Y with mode M, and have 32 megs of ram free for the Java environment to load. If you are writing a commercial application, and you are serious about your company, you're going to use C/C++ and optimize your code natively for the platform you execute on.
My buddy and I have this discussion periodically- he uses a Java based IDE and I use a C based IDE. His IDE takes about 10 seconds to load up when he double clicks a java file, mine takes about 3. Once loaded, they both perform similar but mine seems to respond slightly faster. He is happy to wait, I am not. I use Slickedit, he uses Netbeans.
I wish I had a dime every time someone said "yea, well Java is a great game platform" and my response is- "Obviously. All the best selling games are written in Java, as is the best selling operating systems"
Java is fine for what it does, but given byte code or native code, I will always choose native code. I don't want a JVM.
I would like to add that, while already-loaded JAVA is just as fast as C or whatever, JAVA is an ugly, stupid language. Being forced to use pseudo-object-oriented style with libraries that are hopelesley disordered (both litterly and linguistically) is no fun, period. It takes way too much time to write code in JAVA and results in code forced to a particular methodology, one that isn't even that super to begin with. I don't udnerstand why people dick around with this language when they could use a purely functional one and get not only functional style, but OO and procedural and continuations and better debugging and better, quicker writing of code, as well. The only thing Java has accomplished is getting swarms of incompetent, corporate-whore programmers to work together on software without requiring the use of a brain. And yes, I am a corporate-whore programmer, so I know this is how it is.
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:
Check out Class Data Sharing.
"The class data sharing feature is aimed at reducing application startup time and footprint. The installation process loads a set of classes from the system jar file into a private, internal representation, then dumps that representation to a "shared archive" file. During subsequent JVM invocations, the shared archive is memory-mapped in, saving the cost of loading those classes and allowing much of the JVM's metadata for these classes to be shared among multiple JVM processes."
It's only enabled for the client VM. Incidently, it was developed and submitted to Sun by Apple.
C++ sucks cocks
...and benchmarks. We all know by now how this works. In my particular, unique, case I only have two real-world applications for java. Freenet (http://www.freenetproject.org) and Invisible Internet Project (http://www.i2p.net) It is by coincidence they are both written in java. They are both incredibly cpu and memory intensive. They both have native jni add-ons to speed things up and these native implementations are often many times faster. I suspect the cases where native is much faster still greatly outnumber the few instances where java is faster.
It was only a matter of time before dynamic execution outperformed static compilation. Wake up and smell the Java.
This feature (persistent caching of core library classes) is in tiger (1.5). I haven't benchedmarked 1.5, but startups of some of my favorite apps are noticably faster. Debug, compile and test cycles seem to be about the same for me though...
Read about it here.
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?
Today I spent the whole day trying to parse a 2M plain text document using the regular expressions feature in Java 1.4. I could not get anything done, the thing just crashes. I wanted a "portable" solution very dearly, and I wanted to "do" Java. Sorry, but, like every other time, it just doesn't work. I bought all these books; I really like Java. I just can't get anything done with it in a reliable way without recurring to some sort of trick, or following some "the right way to do Java" advise/book/article. I have not tried other solutions, like Perl or Python, but I am not taking any risks; I'll just settle for C++ and plain finite state machines for now. Nothing better than a tool that works well every time.
Glad I'm learning Java. Of course I've heard that its slowness was a drawback, but I also heard that they're trying to make it faster.
Maybe its supposed slowness was largely a misconception?
The code? Hard to believe without it.
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.
Are you me?
Because I could have swore I was thinking the same thing, except that I am a currently uemployed CWP.
Is it just me, or have there been alot of responses that boil down to "C++ can be fast if you throw away anything inherently C++ and use straight C instead?"
.Net too, are great because they are rich, more than anything.
Part of the point here was to compare two supposedly similar languages. If the author wanted to compare nasty optimized hard-to-read C to Java, he would have.
Java, and
If you really care about speed so much, why are you running an OS to run an application that is a language interpreter (HTML, in this case), the code of which was produced by yet another interpreted program (Perl) that runs through another program (Apache) on top of yet another OS, and which is transported over a low-bandwidth internet connection?
Because it's feature-rich!
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."
Your post reads as if each difference is a point in java's favour, which I don't really see. Perhaps you didn't mean it that way, but that's how it sounds. Really, most of your post sounds more like "I'm more familiar with java, therefore it's better".
C# has one major IDE (Visual Studio) which has a RAD philosophy which *does* prevent some valid C# code being written.
Such as?
The IDE is really buggy
Not buying it - I've used the IDE for several months and not had a single problem with it. SharpDevelop had some bugs, but the MS IDE has not caused me a single problem. Do you have examples?
If this person doesn't know what the error messages mean or where to look to find out then it is safe to assume that they are not capable of writing optimized code. Just look at his hash code. He uses a strcmp function in the c++ code to perform string comparison where as java uses hash based comparison in containsKey function. The fact that Java keeps track of table of hash codes in memory helped its performance tremendously. The code structure isn't consistent either.
One can clearly tell that the gentleman is not experienced in writing optimized code.
-----
One is born into aristocracy, but mediocrity can only be achieved through hard work.
Leaving aside the results or whether the benchmark is meaningful, his presentation of the results in the graph is truly awful. The one large spike for Method Call/Server JVM is so large that all the other results are nearly visually indistinguishable.
He admits he couldn't write a script to automate the tests. That does not inspire confidence in his ability to assess programming languages.
Please.....
I certainly agree that running on a VM with JIT compilation should theoretically be a comparable speed to pre-compiled code (other things being equal). However, I think many people here are putting way too much faith in dynamic optimisation at run-time.
Sure, the VM could watch the code for the most-executed paths and re-optimise for them on the fly. Of course, that's pretty much equivalent to active profiling the first few runs through the code. As anyone who's waited while an instrumented executable profiles a large data set at 1/10 or less of its usual speed can tell you, active profiling is slow. In order to be of any real value at all, you'd have to run-time optimise only the most frequently executed code, with a good choice of how many runs to profile before you recompile it. Anything else is just never going to give you a worthwhile return on your "investment" in profiling overhead.
Basically, there are plenty of theoretically sound and practically evident ways for a VM/JITC approach to be as fast or even faster than a traditional compile-only approach, but run-time optimisation is not one of them; it's much more hype than silver bullet.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
As a gentoo user, C++ and Java programmer I was very interested in this. I noticed one thing though, this "optimized C++ compile command" was only a generic i386/i686 command. I reran the tests with the optimized compile command I use as my CFLAG g++ in.cpp -march=pentium4 -O3 -pipe -fomit-frame-pointer -o out. After doing this I got C++ to come out faster 75% of the time. Probably if I played with the code and optimized the C++ code as well I could get it to run faster. I emailed the author my complete results. If you would like to see them just reply here with your e-mail.
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).
You know guys benchmarks are nothing but gummy bears for vendors and customers! Everything affects a benchmark: programming style, programming skill, TIME spent optimizing the code, machine load, cache size, cache speed, compiler switches, compiler optimisation techniques... and so on and so on... Reduce the struct from 5 bytes to 4 and more blocks will potentially fall on cache, boosting the speedup factor. If you don't have a clear, at LEAST, 50% gap, it's "in the noise" of statistics and not worth even looking at it.
...well for now. ;)
If you want a real benchmark, ask Blizzard (http://www.blizzard.com) to code their next Warcraft IV game in 100% Java. Personally, I put my bet on C++...
Java doesn't have pointers, thus your difficulties.
Anybody got some references?
Now, references we can handle. Haha, get it?! Handle! Hah! Okay, nevermind.
Actually, no it is not. The Fibonacci benchmark measures the language's ability to turn tail recursion into iteration. The Ackerman benchmark measures actual recursion, since a compiler cannot remove its nested recursion. For what it's worth, ocaml wins both the Fibonacci and Ackerman benchmarks by fairly wide margin (Fib: 2x faster than gcc, Ack: 33% faster than gcc). (Disclaimer: I'm no fan of ocaml -- I've never used it. I'm just reporting the facts.)
For fooks sake,
.Net c# on doze vs. Sun's JVM on equiv intel hardware. That's real world, and a hell of a lot more relevant to the (F)OSS community.
I really wish people who develop this mildly insane desire to compare "speed" between languages would at least bother to aquire the compilers and expertise to fairly run the benchmarks.
Mark me redundant, but the Gnu suite has never been about performance, while the Sun JVMs are all about how fast what amounts to an interpretive language can actually run. Side note: IBM's JVMs still smoke Sun in real world apps.
You want to make useful comparisions? Benchmark
You've got it wrong. This is correct:
const double sqrt5 = sqrt(5.);
const double gold = (1.0 + sqrt5)/2.0;
const double goldi = (1.0 - sqrt5)/2.0;
int fibonacci(int n)
{
return floor((pow(gold, n)-pow(goldi,n))/sqrt5);
}
For n > 5, you don't need the goldi part.
"And if modern API's and architectures were designed for Assembly in mind"
you just have no clue huh?
he said pretty, wtf was that?
As mentioned on a previous post, the reason why the C++ test are too slow is because the person who wrote the benchmarks don't even know how to write "proper" C++ programs. Using cout instead of printf for debugging purposes, repeatedly allocating objects within a loop. Native Qt programs can easily beat your Swing-based semi-interpreted app any time.
Maybe in someone elses world, Java is faster than C++, and maybe in their world a narcoticized slug is faster than an SR71 Blackbird (with afterburner) in their world. Not in mine. I've seen real-world java running on my real-world computers. I've seen real-world C++ running on my real-world computer. In my world, Java runs like a narcoticized slug. It's slow as hell. I've heard stories of 'pre-compiled byte code that's real fast'. Bullshit. Fundamentally, java is interpreted and has a middle layer between itself and the machine it's running on. C++ compiles into the machine code the local processor directly understands. If you say 'Java has new algorithms...' I can argue "I can put those into C++". Java is slow. C++ might not be the fastest language for every application, but for most, it's usually close to an order of magnitude (ten times) as fast as Java.
Qt's X11 GPL version is free. A commercial license is not.
c# has fucking xml gobbledegook interspersed with C++/Java style code.
What? "XML gobbledegook" is not a requirement. Please smoke less crack.
C# isn't portable.
Oh? That depends on your definition of portable.
If your definition is "one set of code can be run on any machine", then neither C# nor Java is portable.
If your definition of portable is "it's possible to create a runtime and compiler that will support the language", then C# is equally as portable as Java.
Java's containers lacked an iterator concept until recently
Until *recently*? The iterator support has been in place since at least 1.3, so it's been there for quite a few years now.
And Visual Basic is even easier to use for creating simplistic GUIs, but that doesn't mean that it is better.
Qt's lack of basic design patterns, notification mechanism, relatively poorly designed widgets and lack of flexibility makes implementing anything that goes out of the ordinary a nightmare. The sad part is that Swing is also far from perfect and they are both still among the better GUI packages. I hope SUN rewrites Swing from scratch while keeping its philosophy.
I am surprised about the Java method call performance being so much better than C++. That tells me something weird is going on here.
Java has a LOT of method calls to methods containing only 1 bytecode, which would be trivial to inline. In fact, a lot of Java methods contain only a few bytecodes. So the cost for these methods is close to 0 as the JIT inlines them. Could these methods be tipping the results in favour of Java too heavily? One should probably look at the median instead of the mean speed of method calling. What is the worst case calling speed for Java/C++ ? What if we strip out the outliers?
These benchmarks definitely surprise me. The JIT trashes the cache when compiling methods, and uses a lot of RAM. I know for a fact that cache performance is going to be terrible under the JIT compared to C++. But what difference would that make in these benchmarks?
I'm looking at Java traces right now, and a very small program that does almost nothing contains 15,600 method calls. About 12,000 of that is just API stuff before main is even called. It generally calls the same methods over and over again (e.g. <init> on object, etc etc). This is why the startup time for Java is so horrendously slow.
I don't know, these benchmarks just seem to go against my own experience.
That's a single branch - true / false - so you can take two paths at once. That's not what I'm talking about (and it's not a differentiator between Java / non-java code anyway).
Runtime constants are things a user-supplied value you multiply each cell in a large array by - instead of loading the value from memory, you could use an immediate value.
I always look at these "my car is faster than your car" things.
C is 'the' language.
Assembly is faster (for obviously reasons)
You cannot write a java compiler in java, it is written (and funny, that) in this case in C++
soo.. I would say your benchmarks are probably problematic and not taking enough time or crunching enough data or something.
It is nice that you are all into your language that (in my personal opionion was nothing more ever than a buzzword that got out of control) but really now.. You do realize that slashdot would not print a "C is faster than Java" story because most people already know that, they posted your story because they know that about 100 people will post benchmarks that will make you crawl back in your java hole to lick your wounds.
But, that is just my opinion on this grumpy night..
anime+manga together at last.. in real time.
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.
Any advice for profiling in java? I write some apps, but have rarely done profiling, and don't really know where to start. Suggestions?
Given enough time a C/C++ application will end up beating one in java/python/perl/c# etc but lets be honest in the real world there is not infinite time. It takes a LOT of work to make a fast C/C++ application that has had the memory leaks removed, bounds checked where they need to be etc. In the higher level languages you can implement a good enough solution that is fast enough quickly and it is simpler to debug and fix them.
I have seen a number of apps redone in java/python etc that have ended up a good deal faster then the c/c++ versions where. It also usually takes a month to do what it took 10-12 months to do in the c/c++ version.
For example in python you have dictionaries and because they are so simple to use people tend to use them as a base data structure all over the place and in python dictionaries are probably the most heavily optimized piece of code it has. So the most natural way to make a hashtable is just built in which tends to be a good deal harder in various lower level languages.
Also it is often easier to make a program written in a higher level language faster then it started out with basic profiling since the code is shorter and simpler to read. Overall from what I have seen programs in higher level langauges tend to be optimized more if it is important since it takes far less time to code them and the optimization is usually simpler to see and write.
Computer modeling for biotech drug manufacturing is HARD!
Evidence: programming in C is MUCH faster than assembly.. I don't care how much upfront design you use. Not only is the level of abstraction higher, but the tools are better.
I'd argue that Java is at a higher level of abstraction than C++ and has less distracting features (which waste a project's) time.
I speak from experience: at company X we developed a project with a not so formal programming methodology.. results: slow dev in C++ (we were all highly experienced with the language too)
at the same company we switched to Java. Soon we developed an app using the same not so formal methodology and had much better results in much less time. We thought performance would be a problem but our experience was otherwise. That was at JDK 1.2. None of us knew any Java either at the beginning of the project but learned as we went.
Methology was not a factor.
I'd say my experience and that of some of the other hard core ex-C++ developers on this forum is enough hard fact. Opponents give no concrete examples.
Even before this I had experience in the Smalltalk world. And participated in a Smalltalk dev project and was amazed at their 6 month product cycle. In C/C++ it was always a year long cycle.
Don't underestimate the power of the tools you are working with. (Java has some of the best dev tools too like IntelliJ IDEA)
Finally, you may say that Java cheats because of APIs.. But that is, in my opinion, the point. Java has a zillion APIs.. C++ doesn't. C++ even after all these years doesn't have the API support.. why not? Culture??
Whatever it is.. the choice of your platform DOES matter. Java usually wins in devtime/debug time/ maintenance time.. the metric that REALLY matters to companies. Execution time is usually poor design... in any language.
Why is it you people don't understand that one test, on one platform doing one thing cannot be extrapolated to an infinite population of potentail applications. Count to 10,000 indeed.
Stick to your journal twit. No one will bother you there, and no one will read it, so no one will feel the need to mod you down. You can escape the "M$ astroturfers" in the employ of Bill Gates, living in Bangalore. Really.
Tut, tut.
Turing machines have no real-time input nor any output except one bit representing a function of a string. Thus, the strictest sense of Turing completeness doesn't apply to operating system kernels, which manage all of a computer's input and output.
There are now some ARM CPU cores you can license that support 3 instruction sets: ARM, Thumb, and Java bytecode. Now, some of the bytecodes are implemented partially or fully in software by causing interrupts.
However:
1) You either need to write a bytecode-to-bytecode JIT, or you lose the advantages of runtime profiling and code generation (no de-virtualization, etc.).
2) A significant portion of the speed issues with java come from language features that still need to be paid for in your hardware implementation (gc, bounds checking, all methods virtual, encouraging excessive allocation and freeing, etc.)
3) Almost all Java compilers use very little optimization of bytecode, because they expect the code to be optimized again at runtime. Some compile-time optimizations actually have the effect of obfuscating bytecode so that JITs become less able to optimize (without wasting lots of time with more extensive analysis). You could write your own javac optimized for your particular implementation, but while you're writing a compiler, you could just as easily target it to native code on a CPU architecture that has many orders of magnitude more development funding going into it than your little research chip.
4) Hardware bugs are less fixable than software bugs. Commercial Off The Shelf (COTS) hardware is a huge advantage here. Are you really going to make a hardware Java chip that is going to get close enough in raw native speed to an Opteron or G5 that the JIT needed by the COTS chip is going to tip the scales in your favor?
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.
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?
There are thousands of differences between C# and C, between C# and Perl, or C# and assembly language.
If you can only come up with a few dozen differences between C# and Java, then relatively speaking, they're almost exactly the same.
I wrote two programs, one in java and one in c++ that creates 10000 Hello(String/char *) objects. They just print s to stdout when created.
/dev/null
/dev/null
/dev/null
/dev/null
./a.out > /dev/null
// end of main()
java $ time java Driver >
real 0m0.204s
user 0m0.180s
sys 0m0.016s
java $ time java -server Driver >
real 0m1.191s
user 0m0.476s
sys 0m0.028s
java $ time java -server Driver >
real 0m0.510s
user 0m0.475s
sys 0m0.024s
java $ time java -server Driver >
real 0m0.535s
user 0m0.483s
sys 0m0.014s
Now for C++:
c++ $ g++ -O3 driver.cpp Hello.cpp
c++ $ time
real 0m0.015s
user 0m0.005s
sys 0m0.001s
The constructors where System.out.println(s); and printf(s); where s was "hi".
int main() {
Hello *h = 0;
for (int i = 0; i < 10000; i++) {
h = new Hello("hi");
delete h;
}
return 0;
}
public static void main(String[] args) {
Hello h = null;
for (int i = 0; i < 10000; i++) {
h = new Hello("hi");
}
}
Now i realize, i didn't prove crap there. I mean, there are so many differences its like I didn't even put any thought into it. In other words, this test is just like the article.
A study testing Java to C in speed has already been performed 6 months ago (predating this study). Please check http://web.ics.purdue.edu/~jpkaylor/trig.html for the original information.
i too, am sick of hearing about how slow java is. i think this claim had a lot more validity back in the day ('98 or so) but now it's just echoed amongst the idiots. one thing they've beaten into us in computer science courses, is that optimization is really only needed in a few critical areas, and the rest of the program wont depend that much on performance.
with today's absurdly fast computers, just-in-time compiling and runtime optimizations, semi-native environments (OSX's java, GCJ, JNI, or projects combining multiple languages) -- why must this issue constantly be touted every time java is mentioned?
If I was developing a large (and perhaps distributed) application
What?!?!?!?!!!!!!
You are the exact person why I made the comment above I create and administer clusters. And if you compare distibuted applications everything sucks except for tuned assembly (with C on top) or possibly fortran. I can't believe you said Java would be faster when distibuted.
That was just terrible...
My $0.02
Thank you! Someone had to say it!
;o)
(Glad it was you, because I wouldn't have used those words, I would have covered the ears of the children
My $0.02
As a downside though, I'm not sure how well supported it is on non-OS-X platforms.
The GCC source code distribution includes an Objective-C front end. Are these platforms enough for you? Sure, you don't get the Cocoa/Openstep libraries everywhere, but the GNUstep team is working on that.
(That's not actually true. I like being pedantic. I don't like having to do it in public.)
And Visual Basic is even easier to use for creating simplistic GUIs, but that doesn't mean that it is better.
Ugh, no. VB's widgets are horrible. Full of bizarre and illogical interfaces and behaviors. The only thing VB has going for it is a nice GUI builder.
Qt's lack of basic design patterns
Examples? Which patterns do you think ought to be implemented in the framework which are not?
notification mechanism
Qt's notification mechanisms (signals and slots) are excellent. Very flexible, powerful and simple to use.
relatively poorly designed widgets and lack of flexibility makes implementing anything that goes out of the ordinary a nightmare
Sorry, but I can't agree with these generic complaints. You'll have to be more specific. I've found that Qt's widget set provides a great deal of functionality, and as far as the design goes, I usually find that I can use them without referring to the documentation beyond a glance at the method names. That's a sign of very good design. The widgets are also easy to extend, and having the source means that there is ultimately nothing you can't do.
I have used lots of different GUI toolkits over the years, and Qt is one of the best ones I've seen. In fact, it's at least as good as everything I've used, with the sole exception of the NeXT toolkit.
Maybe a good place for you to start would be to point to a GUI toolkit that you think is better than Qt. MFC?
Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
The study supposedly was not designed to highlight the benefit of Java but to benchmark for comparison the two languages. To do this accurately, compilation advantages should be leveled out. For an analogy, if you wanted to accurately compare the skill of two race-car drivers, they should be tested in identical environments, same track, car, weather conditions etc.
-- "Someone's gotta go back for a shit-load of dimes."
Qt's X11 GPL version is free. A commercial license is not.
Nope. But it's quite reasonably-priced, as professional development tools go. Well worth the price. A much better value than the Rational tools, for example.
Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
Try: // Use OS L&Fn dFeelClassName());
:/
try {
UIManager.setLookAndFeel(UIManager.getSystemLookA
} catch (Exception e) {
if (DEBUG) {
System.err.println("Unable to set Look & Feel");
}
}
I mean its still as ugly as hell but now it looks more like the native OS, just don't expect it too like the version your using, more probably a few revisions back
GPLv2: I want my rights, I want my phone call! DRM: What use is a phone call, if you are unable to speak?
Pascal and C are about as similar as are C# and Java. In many regards, they are the same class of language, but there are still features that may be must haves or must-not-haves in deciding between them.
Intel C Compiler, with inter-procedural optimizations enabled, produces code that's almost always 20->30% faster than g++.
Remember that ICC's speed is hampered by the time it takes each user to flip enough burgers to earn money to afford a license for ICC. This will be true of any compiler not available under a gratis license.
"Well then use the Linux version, which is gratis for non-commercial use!" You refer to the "Non-Commercial Unsupported Version", which exists for GNU/Linux but not for Microsoft Windows. Virtually all store-bought computers contain Microsoft Windows, and many contain hardware that happens to be unsupported under GNU/Linux. Replacing this hardware with new hardware also requires flipping burgers, which takes time.
Processing power is cheaper than programmer time, and increases at an exponential rate.
As this trend continues, requirement for optimised code will only lessen. If you spend a month trying to get a 10% speed increase by optimisation, you're barely keeping up with hardware advances...
Sure, there's games, etc that need quick code, but even then, the old axiom "90% of the time is spent in 10% of the code" applies.
Write the 90% in a high level language of your choice, and optimise that remaining 10% *if required*. That 10% is largely covered by libraries such as directX, openGL, etc... even game developers do this these days to an extent - no longer are games written in 100% assembler. They've become too complex for that.... and are now mostly C with hotspots optimised as required.
At the end of the day, pick a language that is easy to code/debug, and suited to the particular task you are trying to accomplish.
smash.
I run: Windows, OS X, Linux, FreeBSD. Just because you have a hammer, doesn't mean everything is a nail.
"shoots the compiler into the foot" hmmm...a foot cannon...interesting :)
-- "Someone's gotta go back for a shit-load of dimes."
I agree. Although I have never programmed in Assembler, I can understand it when the need to debug through it arises. However, more importantly to the needs of a typical business, I would suggest investing the time in improving the current programming skills of the developers (whether it be Java or C++) and get them to be able to code effectively, rather than shoe-horn them down the route of an 'elite' language such as assembler, just because, at the end, that coder will be somehow deemed more worhtwhile.
It matters little in the majority of applications what language they use as long as it gets the job done within acceptable metrics. Most of the time, it's not the code that is at fault, but the usage of the DB (in my experience).
My personal preference, knowing both Java and C++, is C++. Yeah, C++ is a monolith of a language, and the mass of different ways to do the same thing can be a detrement (especially to novice coders), but when you learn the better ways of achieving particular things is becomes a joy to use, while still being maintainable. However, I can see the advantages of using Java, and it's basically a case of using the tools that match the needs of the organisation.
To see what I mean, head down to your local computer store and fire up your favorite application on a 2.4 GHz and a 3.1GHz machine. [description of blind testing method follows]
Given an emulator's numerical frame rate indicator, and given that an emulator showing a complex scene on one display might dip below the display's refresh rate on the slower machine, causing visible jerkiness, I could probably ABX the machines at 18/20 or better.
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]
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.
The Java language is also a shorthand for bytecodes, but those bytecodes are helpless without a virtual machine.
The C language is also a shorthand for opcodes, but those opcodes are helpless without a virtual machine.
Modern x86 processors treat opcodes as bytecodes for a virtual machine, translating them into something that the processor's more RISC-ish backend can use. Some even reorder the operations. Just look at the microarchitecture of any Pentium 4 or Athlon processor; the P4 even has a "trace cache" to store recompiled micro-ops. Transmeta's processors go even deeper.
You assholes really are out of control. I hope you are pleased with yourselves, but it does not matter, Microsoft is doomed. A man can only disgrace himself and you morons have done a good job of it.
I used to use Emacs a lot. I use jEdit mainly now, because I really like it; it helps me work faster. But I definitely don't use it because it's fast. It's not. jEdit isn't as slow as Micro$oft Word (substitute 'tu' for 'wo' to see my opinion of that "program"), but it's pretty darn slow. It's so slow that, although I liked the program when I first tried it, it was just too slow, on every platform I tried it on (Linux, Windows, OS X). I've got past that now, because slow as it is, it helps me work faster.
Know why jEdit is slow? 'Cause it's written in Java. Every Java app I've ever used is dog-slow, especially compared to C++ apps. C++ was designed to be fast; and when used properly, it is. Java was designed to be portable; after several years, false starts, marketing hype and outright sabotage, it pretty much is. But it wasn't designed to be fast. That's not the point of it. It's designed to be portable and easy to program (and to make lots of money for Sun, somehow, but that's another topic).
This guy may have thrown together a benchmark, but I've got a better one: experience. Wake me up when jEdit runs almost as fast as Emacs on the same machine; then I'll start to believe this stuff.
And yes, I know Emacs isn't written in C++; it's written partly in C, partly in Lisp. So most of it's interpreted. (Some claim that Emacs stands for "eighty megs and continuously swapping".) So I think this is a way more than fair comparison.
If you're using gcc 3.3 for this comparison, then you're truly picking a lame implementation of the STL. No wonder Java is even _close_ to C++.
Try using something with a more optimized STL, like the free STLport from STLport.org.
I think everyone has pointed out in many ways why these tests and comparisons were flawed. Much of it boils down to deciding what exactly "C++" is and what exactly "Java" is. IN fact, I don't think either of those terms is even specific enough to build benchmarks around.
With C++, there is the language syntax, the standard libraries, which compiler you use, which optimizaitons you chose, etc. Within Java, there is the version, the libaries, the VM vendor, the VM optimizations, etc. And then you have to consider that some tests might perform better in one of the languages on one platform but the reverse on another -- where the platform might be OS, hardware, or both.
And then how you measure "performance"? The first execution? Subsequent executions? If you ask a business manager, they might include time-to-develop as a performance measurement. OR howw about time spent mediating the religious war started in an IT department over which language to use???
The Halting problem is just a decision problem - it is NOT an algorithm.
"An algorithm is an understandable and finite set of instructions for accomplishing some task which, given a defined set of inputs, will result in some recognisable end-state"
It can be done in constant space, saving a malloc() call. Does this version run any faster?
Imagine that. How evil of him, and how self-defeating of Slashdot to post it.
Now, go back to your meds.
Just a little FYI... also, so is ECMA-script, and the CIL, IIRC.
THIS THING CAN TURN ON A DIME, MACROSSZERO STYLE ALSO FUCK BETA, ~NYORON
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!
You just proved that the results of a trivial test are trivial.
Clues in order:
The article is a troll. It was designed to FUD Slashdot. Well done, assholes. Between this and Google bombing, it will be harder for some of us to learn. Whatever Microsoft is paying you for this stuff is too much. This is as transparent as the Apple Switcher.
Interestingly enough, the trolls are also wrong. Now that the article is visible, people are picking it to pieces. I doubt people are going to walk away with the wrong impression.
In any case, I could care less. Java is non free. As nifty as it is, I can do the same things with free code. Even if java was faster at this and that, the fact that it's not free makes it a dead end. Sun's not an evil company today, but they can become one tomorrow. Why would I put my work in their hands when I can own it myself?
Friends don't help friends install M$ junk.
Ok, first off, I write software for a living. So my main issues are deadlines, productivity and total cost of production. And guess what's gonna win over, when given the choice between picking a compiler that's 1.2 ms faster in "certain" "controlled" situations or having a nice elegant language that scale properly and is easy to maintain.
Imagine trying to tell a customer, well I can give you the app in 3 days for 10K that will run fine on you new $300 Celeron's or you can have it in 3 months for 100K and it'll implement (insert geeky mathematical function) in a more efficient manner.
I get the feeling that you guys bitching about the very minimal difference between these languages, are either A) Writing only low-level libraries. B) Regurgitating whatever tech website you read about earlier today. Or C) Have no "industry" experience and have nothing better to do than try to skew opinions one way or another.
Who fucking cares? Tell ya what, I'll use one of the highest-level language out there (Delphi or C#). You use your Java or C++ and we both start on an intensely complex and graphical database application on the same day. Not only am I going to be done days maybe even weeks before you, but the consumer is not going to know that your application runs slightly faster, more efficient, or even 5x better.
Just my 2 cents.
My mother never saw the irony in calling me a son-of-a-bitch.
You might say that that's what JVMs do. But ... you're wrong. Simply translating java bytecode into machine code doesn't get you much - i.e. you're only marginally faster than interpretation (that's a research result from IBM). What you have to do is to reconstruct the data and control flow from the bytecode, and only then do the actual compilation.
The same is pretty much true about x86, if you want to get good performance out of it. That's mainly the reason for x86-64 and Itanium - both actually clean up the instruction set.
The Raven
These two examples do different things. One must do a proper conversion from int to string, and the other is a simple math operation to cast from int to char.
I think the point you were trying to make is that the C++ stream library is slower than the C file I/O library. Yes, genius, it generally is, but only by a small amount.
You miss the point about the duality of C++ - it's both low level and high level. I can use classes when I want object oriented designs that encourage reuse and are easy to maintain, but I can still use C coding techniques when I really need extreme performance.
Automatic double-optimized code +bonus language and platform portability?
Hey, if it works, I'm down.
CAn'T CompreHend SARcaSm?
You write: "the more people who know about present-day Java performance, the better"
Why do you think so?
-- Watch me working: www.magerquark.de
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.
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.
Most real world applications I can think of do not have a constant high CPU load. They typically have short peaks of loads and plenty of quiet moments. In such a load pattern, garbage collection can be performed when the load is low, and the GC hardly impacts performance at all.
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...
If you write highly modular code and only use the -O2 setting for optimization. I'd have used something like "-O3 -fomit-frame-pointer -funroll-loops", which is what I compile almost everything with. The JVM does loop unrolling and inlining, which gcc doesn't do when using -O2.
With the exception of the object creation benchmark, I believe that the results would favor C++ if the optimization flags were not so crippled.
So, yes, OK, default object creation in C++ may be kinda slow. But the power of it is that you can define (and quite easily at that) your own memory allocator, the C++ version will fly, leaving the Java far behind.
And you can write a fairly generic and fast memory allocator for C++. One was published in DDJ, January 1999 (disclaimer: I wrote this).
C++ is lame, so, for the race to be fair, Java has to have one leg strapped behind its back? Rubbish. Java CG is supposed to defer memory stuff into efficient rare operations rather than faffing about with allocation and deallocation in the antique manual style of C.
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.
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.
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
instead ofI 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.
Ok, here is the java version
/usr/bin/j2sdk1.4.2_04/bin/java -server sieve 10000
... ./sieve 10000
./sieve 10000
/Alex
[alex@alkis dev]$ time
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
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
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!
It might be that the grandparent post were referring to the foreach construct in 1.5, which allows you to do stuff like
While these tests do indeed show that using Java is faster then GCC (which is largely not processor optimised) code written by a java expert with very littel understanding of GCC, it really dosen't 'prove' anything for several reasons.
1-GCC is not as optimised as other C compilers
2-He's a java expert, but a poor C programer
3-his implimentations as a result are better on Java, and worse on C
So, what I think needs to be done- is for somone to grab the most efficent implimentations (on java and C), send them to him, and ask him to run the test again, so that this way we skip the optimization problems
As for the GCC problem- I think that GCC is more 'ideal' due to the following scenario- code written in GCC is, at least in theroy, portable to multiple arcetectures- much like a java program; the dammage to performance for that factor should cancel out; IE- were testing two multi-plantform languages, not a platform specific one against a multi-platform.
These opinions are not my own- I have blatently copied them from others in the thread, but it should help people see what the argument is.
-Millions of Monkeys, Millions of typewriters, 6 hours of sorting through faeces encrusted pages to find: This post
I had only a brief in the handling of the example code for matrix.cpp file. This code a fine example to slower the performance of code. It is always a bad idea to handle a matrix as a two-dimensional array. Doing so will cause the processor to performe complex calcumaltion of the size of the object. Any experienced coder would use a simple array and small method to calulate the position Something like
return (iPos_x + iPos_y * iCount_x)
Well, I hate Java. I get sick to my stomach when I recall writing a full EDA CAD program in Java, just to see if the language is worth bothering with. I will in fact pay a "mugger" to smash my hands with a hammer and become a burden on the system before I write further code in Java.
.NET solution using C# if I needed the features in Java that I respect. I just don't like the Java language, it feels like a toy.
That being said. I like apples and I like oranges. I don't compare them to one another since they each have a unique "being". I do compare the apples within a basket and choose the one which appears most interesting to me. Other times I do the same with oranges.
I like to develop operating system kernels, web browsers, ans other end user applications. I don't care much for coding web back-ends. I believe the web is obscenely overused for things that would have been better implemented as an application.
C/C++ and Java are apples and oranges as well. People insist on calling Java slow. Or they brag that C++ is faster. The fact is that given the modern architecture of a JVM, there is no reason to believe that Java is slow. It really is no longer an interpretted language. It is a language which is simply compiled into an intermediate language before becoming an executable. A modern Java VM typically will compile all the code to native when loading a module. The next time the module is loaded, the native compiled version is pulled from a cache instead of recompiling. This means that the Java language in some cases for performance is in fact superior since the compiler group can focus on compiling Java to an intermediate language which another team can focus on compiling and optimizing to the native architecture.
C++ is also an extremely complex language to implement a compiler for. The preprocessor followed by lexer and parser are extremely difficult to implement. The back end is also terribly hard to design. There are so many differing contexts in C++ that developing an excellent C++ compiler is far more complex than making a Java compiler system.
Java also offers garbage collection. There are top notch people around the world obtaining Ph.D. degrees in this topic alone. It's far more advanced than a simple reference counter. Constant evolution is occuring making Java garbage collectors kick in at the right times and function quickly. This solves a huge problem related to C++ heap managers. C++ heap managers are incredibly slow. There are of course some heap managers which are much higher performance. Doug Lea's malloc is fast, but not thread safe. There are thread safe incarnations, but they're not as fast. There are commercial heap managers such as SmartHeap which are in fact fast and thread safe, but expensive. In heavy object oriented systems such as web browsers and such, it is likely that performance is going to be hurt severely by heap management and a Java implementation therefore can definately be faster since cleanup typically will only occur in out of memory conditions as well as idle times.
I still can't imagine any project that I would implement using Java. I would chose a C++ system instead. It has nothing to do with performance. It's just that I find Java to limit my choices drastically. I would prefer a
Obj-C++ is an Apple extension that lets you mix and match Objective-C and C++ code transparently and easily, and was just given accepted status by the good folks maintaining the gcc source base. (Not a standard include, but one to be standardly distributed and enabled with the --enable-languages flag at compile time of gcc.)
// Objective-C // C++
You can then do tricks like:
NSString str = [NSWindow getTitle];
cout str.c_str();
Very slick, lets you quickly use existing C++ code and libraries while leveraging the new language.
And they all have free-form windows, and ignore your system supplied font settings, and don't pay any attention to your current display size, bitdepth or resolution. Like Windows XP Home Edition for a 14 year old female AOL user, but much much worse..
Take a look at my java code sometime. I was recently reading an article on java performance and found that I do everything the way that I am NOT supposed to...
Well, at least people find my code easily readable/maintainable.
Uh, no. Java != JVM.
That's the point. A C++ compiler with a JVM backend and your argument is moot. AND with C++ you have the advantage of using it for lower level things.
What the mother of blue fucking blazes is that shit when it's at home? Christ on a fucking pogo stick, you think that doesn't look like a sick dog took a shit on a hot highway at noon? It looks like Plan9 on a bad day!
People like you (Color blind, asthetically blind, unable to grasp simple design principles, idiots) are the primary reason why Linux user interfaces suck shit. You're fucking deluded or possibly on acid if you think that pile of dog droppings looks good.
let me get this straight.
Run a copy of the program.
Either a program with input halts or it doesn't.
If it does halt, then we return true.
Otherwise, keep track of all past states of the LBA, and if we ever come to the same state, return false.
PROVE: if an LBA does not halt for a given input, then it will loop through the same state.
Posters recognized by their sig,
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.
Your obsession with twitter lends validity to his points. Aren't you a Microsoft spy?
Sure you can turn C++ into Java, after all that's how the thing's made, it's compiled from C or whatever. The test is how the standard language fares. Thus eg, using gjc to "enchance" the java by precompiling it would be cheating too.
So wrong that it's not even funny. You know why people aren't advocating buying never hard drives to speed up your compiles? Because compilation is not IO-bound, that's why.
HAND.
The "generics" introduced in Java 1.5 are not generics, incidentally.
Theoretically *AND* practically, you're wrong.
1. Theoretically, the JVM is equivalent to a finite turing machine and thus able to run C++ code.
2. There exists such a beast already (but is sadly not up to date and only a small prototype!).
See here:
Java backend for EGCS.
3. There is mips2java which converts GCC mips backend code to the java virtual machine. Google yourself. But this is a kludge, albeit a nice one.
Many people here have argued that C++-code can be optimized to run many times faster than JAVA-code. This is true, in many, if not most cases. The question is, how fast will the code run when you did not take the time to optimize the code to the fullest? You can probably put in more optimizations in your C++ code, but how much time will it take you, and will it really be worth the effort? Some people also remarked that this benchmark tests the OS or the libraries (IO) more then it does the language. True, but can you truly seperate them from each other? You can choose to use a diffirent library, that you know is faster, but I think many developers will stick with what is deliverd with their programming environement. Not many developers have the time to evaluate other implementations, let alone write their own. A third kind of remark that i read, was that you can't really stick these performance figures on the language as such, but that it are really the compiler, linker or VM that you use that do matter. The example was given that if C++ would run in a VM and JAVA would be compiled that the figures would be quite diffirent. This is true, but it is currently not the case. So, I think it is good sense to compare the languages, since each has its preferred/default strategy for being compiled/executed. So, is C++ faster than JAVA? If you put in the extra effort of optimizing, then yes. If you don't , possibly. Is that effort justified? That depends.
Funny how nobody can say anything negative about anything on slashdot without being labelled a troll. Java has crashed my computer for the past several years, and now it's crashing my cellphone. Either there are a lot of sucky Java Coders, or the language itself sucks.
"Jeremy, you need to get to an internet cafe and cut and paste some appropriate sentiments about me from the world wide
I know Im going to get Troll for this.. but..
..
.. Saying that Java is faster is to shoot your foot, how can anything with more abstraction layers be faster then something without these checks, and without these code in the memory? I dont understand. Allocating alot of objects in java drag with alot of mutexs and so on. Allocating a piece of memory in C drags with some meta information about size of allocation, but so does it in the JVM also. And I never sofar seen any JVM that actaly optimize the code while its running.. Im sorry but I just havent seen it.
If you want to write a big system with alot of developers, and you cant realy afford to huntdown memory allocation problems you use Java. (Not compleatly true, at my company we found some nice JIT bugs..).
If you can live without boundery checking, if you can live without objects, if you can live without segfault checks (null pointers exceptions).. then use C.. and I dare you, you will get more performance just cause C uses lesser abstraction between the code and the hardware, but it takes longer time to learn and program in.
If you can half of half, (the best of the two worlds?) then you can go for an OO C alternative, C++? Object C?
You all see, when it comes down to what language you choose it comes down alot to maintainance, and maybe Java wins there. Java is dead simple, but JIT bugs arent =)
Performance come mainly from one thing, and thats good algorithms. You can do wounders with good algorithms compared to bad ones. If need to squeese even more performance out of your program, you gotta change language, its as simple as that. Change from Java to C++, change from C++ to C, change from C to Asm.
Performance is not everything.
this is ruducilous, just yk teh articel.
"teh Java is bettah tahn teh optimiz0red C++" my ASS!
Java is gay.
... just shut up.
I am truly sorry for you; it's nice that you justify it, but really
Thank you.
Great, now all of those people who couldn't get a C++ program to compile and link will be writing enterprise Java applications.
That was meant to be funny, but I think that it's true to a large degree. Java insulates you from so many aspects of the machine that it allows people with no formal training to make unholy messes out of applications. That's all well and good unless you're stuck on a team with such people.
Oh well, I imagine the assembler hackers were saying the same thing about C.
How? Without examples, your post is essentially a troll. I'm far from Swing's biggest fan (though I have an enormous appreciation for Java after starting out in C++), but throwing together a reasonably complex GUI either by hand or with one of the many (more than QT) visual editors is not hard.
SWT are still FAR slower than QT or the Win32 API
Er no. SWT is the native GUI. Its a library that allows Java to use native GUIs via JNI.
Saying SWT is FAR slower than something like the Win32 API is like saying that Win32 API is FAR slower than the Win32 API!!
My only question is, did he come up with the title before or after he started his testing?
I have studied java in some detail, and my major complaint with Java is not the code, but the JVM. On a windows box, to launch java related stuff, the system has to start the virtual machine which is the painfully slow part.
I think C++ being closer to machine code than Java would make C++ faster, but would have to read more of what other people have tested regarding actual operation speed of the code.
Java is a powerful language, and despite my major complaints with it, I have to admit that it will most likely find itself in more embeded devices such as cell phones.
Just my $0.02
before any retard ever claims java is faster again, just write me farcry, halflife2 level of game in java!
that the individual who published this study (Keith Lea) is the the son of a well known Java advocate and Sun Microsystems consultant (Doug Lea)? I'm not implying that this should in any way taint his results. I just found it interesting that Doug Lea was mentioned in this thread by someone listing the pros of Java, and the connection was never made.
but throwing together a reasonably complex GUI either by hand or with one of the many (more than QT) visual editors is not hard.
Throwing one together is easy, but making it fully functional isn't. For one specific example, have you ever tried to build a dialog with a fairly complex set of controls in Swing that resizes nicely? The whole BoxLayout thing works well and is easy to use as long as your UI fits a certain pattern, but anything that doesn't is pretty hard. Beyond that, Swing is full of little oddities and inconsistencies that trip you up. One that I stumbled across not long ago is that when Swing calculates the preferred size of a pane containing two Boxes laid out vertically, it inexplicably only includes the size of the top box. Setting the pane to its preferred size should require:
But, in fact, it requires:
I'm sure there's a reason, and it may even be a good one, and I could look at the source and find out. But it's not what I expected.
Swing frequently and consistently violates the principle of least surprise. It's always making me scratch my head, even after reading the documentation, whereas Qt not only rarely surprises me, I frequently find I don't even have to look at the documentation because my guesses as to how it will work are nearly always right.
In a nutshell, I've used Qt more than Swing, but spent far more time reading Swing documentation and Swing source code than Qt documentation or source.
To provide some more examples, I'll ask one of my colleagues who has used -- and been frustrated -- with Swing far more than I have to chime in.
Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
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.
Somebody PLEASE say that this dude made a bad choice for the C++ compiler. PLEASE say it again. I need to read it just one more time for it to sink in.
give us a link. Some PHP or Perl or JSP site, or some project you've contributed to, or your personal project page or some commit log with your name.
Sure, I'd love to have you assholes do the same things to me and mine what you do to Slashdot. Why don't you check out all the fine code at:
This site.
Friends don't help friends install M$ junk.
But that doesn't mean I have to be an ass and use more terminology than it's needed, so more people (and not only people with CS backgrounds) can understand.
If you read my post, you will see I mention the H.P. (that was explained in a parent post) and the rest is understandable for almost anyone with, say, secondary education. I believe it's all the education you need to understand this.
You may have CS background, but your divulgative skills are lacking. Otherwise you wouldn't assume all slashdotters understand what is dynamic programming, or probably you're some elitist mofo who likes to show-off in front of everybody.
HAND (Have A Nice Day)
BTW, I happen to be working on benchmarks for some complex, resource-intensive java software. I tried the switch from -client to -server. It made some things a little faster and some things a lot slower. Using -server may have made a big difference for this guy's benchmarks, but it should not be assumed that it will be better for all applications. Test it and judge for your particular app before making this switch.
"I don't know half of you half as well as I should like, and I like less than half of you half as well as you deserve."
... is here :
http://shootout.alioth.debian.org/index.php
BTW, the maintainers of the new version of the shootout seem to be listening to new suggestions.
I suggested a wiki in order for people to add new implementations and/or discuss optimizations.
And they did it !
So now everyone can add his own grain of salt to the shootout.
First off, let me say that I like Java a lot and use it more than any other language. I have done some pretty massive swing projects. For instance I wrote the editor that is used to create the documents that describe how to assemble space shuttle motors.
I have also used Qt, but not as extensively. I have found Qt to be easy to learn, well documented, and logical. Swing is not easy to learn, is reasonable well documented, and is usually but not always logical.
Throwing together a GUI in a visual editor is very easy in Swing. I haven't done this in Qt. However, the visual editing tools that I have used simple place your components statically, with a set location and size using a null layout. If you resize nothing happens. In order to get good resizing behaviour you have to use the Box and BoxLayout objects. Not only are these poorly documented, but the concepts are poorly named. What is a Box? What does glue do? Not what you would expect from the name. Creating a layout that behaves properly by hand is a painstaking process. If you screw on thing up you'll get bad behaviour that is hard to debug since Swing components tend to behave inconsistently on resize, ie you start at one size, change to a second size, and go back to the original size and your components are laid out differently now.
I have fond memories of using Power Plant to effortlessly lay out GUIs that could resize and looked nice back in the day. I don't know why Sun hasn't gotten something that works well for Swing.
Doing layouts by hand in Qt is much easier. The concepts of the layout tool are easy to grasp and work correctly without lots of tweaking.
I could go into a whole page of complaints about the Swing text package and the abomination that is the document tree, but I will save that for another day. Suffice it to say that it is poorly documented, badly designed, and gives you complexity without functionality. Of course adding that functionality yourself is impossible because of the way that useful methods are private or package private so you can't call them in order to do things yourself. The option would be to edit the source, which would mean that you could never upgrade your Java. Ugh!
Lasers Controlled Games!
without a chance in hell of earning a living or doing anything useful in his life. Poor little Twidder.
The Java regular expressions feature is documented at the Java web site. Check out the Java forums for more detail. We have all had trouble learning new APIs and becoming familiar with new languages. But, it is worth the time to learn Java.
I don't know from where your impression about SWING performance comes .... neither on my MAC nor on my PC SWING applications (like CodeGuide, www.omnicore.com) seem in any way slower than native apps.
... well it crashes ugly if n is reasonable higher than max.
... well, I can rewrite it to java if you like ... so the Java version has no recursion anymore.
.... the rest of your comment will then be proven wrong as well: Java will never be faster than properly optimized C++ compiled with an intelligent optimizing compiler except in bizarre corner cases.
.... gues what? The interpreted MACHINE CODE is faster than the native executed machine code .... after the VM has optimized it more and more. No compiler can do that.
Regarding your fibonacci example
For you that example might be "optimzed" for C++
Guess what
Java does RUNTIME optimization. C++ CAN'T do that. As long as C++ is not compiled to a VM it will fall more and more back behind Java the more the hot spot optimizations get improved.
HP uses VMs to run PA-RISC machine code on VMs
Just drop the bullshit Java versus C++ arguments. The question is not and was never: Is Java as fast as C++? The question IS: how long can static compiled code remain faster than JIT compiled byte code or ahead of time compiled byte code or hot spot compiled byte code? Thats the question. And the answer is: in the year 2004, static compiled machine code is no longer state of the art. Hot spot like Sun does it currently is "state of the art" and the dynamic compilation/optimization HP is doing is "bejond state of the art". Static compilation has LOST. (And it was predictable in 1998 that it would have lost around of today)
angel'o'sphere
Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
PROVE: if an LBA does not halt for a given input, then it will loop through the same state.
An LBA with k possible characters per cell, n cells, s possible states of the head, and p possible tape positions has p*s*k^n total states. This finite number of states is the major difference between an LBA and a TM. Therefore, if you run the machine for p*s*k^n + 1 states, it will have either halted or gone through a state more than once. The tortoise-and-hare method is a convenient optimization derived from a method given as an algorithm in The Scheme Programming Language to detect cyclic lists.
HA Ha HA Ha HA Ha HA Ha HA Ha
HA Ha HA Ha HA Ha HA Ha HA
ahem...
"turning espresso into code..."
Er no. There's still a fair amount of wrapping that needs to be done.
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.
...program in assembly.
you get all kinds of speed from that
Actually, the results are surprising, but it is an apples to oranges kind of comparison
Of course it possible to transform a function of the type
:= f (a_n)
into
a_n := g (a_0, n)
This is not the question. By using a recursion the problem is: Does it makes sense: How much Stack I will need in worst case scenario? How much the calls, pops and pushs will effect the performance? Is it worth to pay this prize? Often enough I would say: Yes, but not always.
a_n+1
Er no. There's still a fair amount of wrapping that needs to be done.
No. Part of the design of SWT was to ensure that there was absolutely minimal wrapping. API calls in the native GUI (e.g. SendMessage in Win32) are mapped directly to identically named API methods in the Java implementation of SWT for that platform. Then, an thin object layer of the GUI above that provides a common model of the GUI for all platforms.
On windows, something like the '.setText()' method in SWT is a call to a Java SendMessage which calls the Windows SendMessage function via JNI.
It doesn't make much sense to do line-for-line comparisons between Java and C++ and then argue over the results. A more productive approach would be to define a set of requirements for a real-world application, and then set off to develop a version of this application in each of the two languages. Each implementation may take advantage of whatever features its language has to offer, including it's own standard library.
The results of this activity should be measured objectively based on speed, memory usage, correctness, stability, and the amount of time required to implement it.
As a follow on, it would be interesting to add additional requirements in order to evaluate how well the implementation can be extended and/or modified.
This would make for an interesting competition, and would be alot more fruitful than this discussion.
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."
Just goes to show you how worthless these benchmarks are unless you have an expert implementing for each language writing code like you would in real life and the tests aren't aimed at the benefits of one language or another.
Have you never heard of self modifying code? Look it up. You can do it in c++. You cannot do it in Java.
But really, the question here is whether a generic run-time profiling algorithm can outperform a human with time on his (or her) hands and a good profiler. Why isn't Carmack writing Doom 3 in Java? Is it because he is biased and religious? Or is it maybe because the performance isn't there?
With c++, you can take advantage of architecture specific optimizations. What you are talking about are algorithmic optimizations, which are good, and make java perform better than it otherwise would, but can't approach the performance that a skilled technician in the art can get from c++ by writing well optimized code and profiling the actual generated assembly code.
Furthermore, the specific optimizations you name could be implemented in c++. The compiler won't do it for you, but a clever enough developer could do them, and the end result would outperform Java because there isn't a virtual machine profiling the executable constantly, trying to figure out what to do.
My point is that proper design-time optimization is going to be better than compile-time optimization no matter what. No algorithm can yet approach the intelligence of a human when it comes to optimizing.
We're arguing about seperate things. You seem to view optimization as something the compiler does, and this seems to be a common view amongst java programmers. Real optimization involves knowing your compiler, knowing your architecture, and writing smart code to take advantage of both. No matter how smart you are, you can't take advantage of your architecture in Java. You have to rely on Java to do it for you. The whole point of java is to remove you, the developer, from the architecture.
WWJD? JWRTFA!
There's no difference between an interpreter and a compiler in this case. Both take some Turing complete human-ish language (source code) and convert it into Turing complete machine instructions, which is all that the CPU understands. You could do all sorts of crazy things, a C *interpreter* written in Excel macros, for example. It just takes source and turns it into machine code, and the only question being addressed here is which technique results in faster ultimate execution of machine instructions and interactions with memory, the C++ source compiled into a wad of machine code in advance approach or the Java source compiled in advance into a wad of bytecode which is then compiled incrementally and cached by a JIT process approach. Each one allows for a different set of optimizations that convert the intent expressed in the original source into the closest thing to the minimum work the processor needs to do to carry out those intentions.
"Those who have never entered upon scientific pursuits know not a tithe of the poetry by which they are surrounded."
SWING tends to get slow when many controls are used. I am not sure what the specifications of your computer are, but try running a complex Java GUI app (one which is similar to a non-MFC Win32 app or a QT app for comparison) on a slower machine, or write up a quick test program which plays with 15 or so controls (hiding them, moving them, adding/removing data, creating them, etc.) a set number of times both using SWING and using the Win32 API or QT. SWING is quite a bit slower. Perhaps this has been improved in 1.5, but it is certainly the case in 1.4 and earlier.
Regarding SWT performance, I've yet to see an example of a responsive, large SWT-based GUI app. Eclipse, while it is very nice in many ways, is slower than a dead slug stuck in frozen molasses compared to Microsoft Visual Studio or KDevelop, at least, in my experience. Perhaps I will have to try a server VM.
I can see that runtime optimization has a few minor advantages. For example, a JVM can utilize processor-specific optimizations even if the CPU type is not known at "compile" time. That said, C++ and other compiled languages can do the same if the architecture is known (-march=). Because optimization is done at compile time, optimization time is not a very important factor, and the compiler can freely tune the hell out of the code. What optimizations can a JIT compiler do that a non-JIT compiler cannot? Let's say it sees that a function is being run quite a lot and the JIT decides to inline it. Well, C++ compilers are very good at guessing which functions will be run very often and inlining them, and the programmer can explicitly state that the function should be inlined if desired.
Does the JIT try thousands of possible ways of executing the same code to see which is the fastest? That would be something that a C++ compiler cannot practically do, but compiled language optimizers are so finely tuned that I doubt there are many instances where a modern compiler, particularly an intelligent one such as Intel's or Compaq's, choose a path that is significantly slower than the best a JIT can come up with. That said, compiled languages would not have the overhead of optimizing the code at run time, not to mention the overhead of initializing the JVM. I realize that the latter is just at startup, but startup time is a problem in many modern applications more than run time. OpenOffice is a good (but extreme) example.
Further, Java lacks direct access to pointers, which allow for many snazzy optimization tricks, and cannot compare with compiled languages for bitwise operations.
Perhaps I am not a sufficiently talented Java programmer, but I know of no way to do something like
in Java, and I doubt that Java's JIT could figure out a similarly fast way to convert an ASCII character to uppercase, let alone a more sophisticated algorithm.
Granted, in the RealWorld, developers do not often use ugly optimization hacks for readability and maintainability reasons alone. In those cases, pretty code in Java and C++ are likely comparable. Java probably has the advantage in many situations (as shown in the benchmarks in the article), but Java is a higher level language--It is much more removed from the machine, and as such, can never consistantly beat a sufficiently talented programmer until JITs begin including AI.
Because you can have a strong measure of control over the code that is generated (going so far as to use inline asm if needed), there is no situation in which Ja
Computer Science is no more about computers than astronomy is about telescopes. --E. W. Dijkstra
To be honest I haven't done a ton of Swing lately (I think it's too slow on a 1.6Ghz T40)--for the little GUI projects that I do I use SWT. Much faster and native look and all that. So while my recollection of Swing development may be a bit dim, I'm familiar with working with a new GUI toolkit.
SWT has it's own layout manager similar to GridBagLayout in Swing. At first it seems like complete rubbish, but after a while it makes sense. The point, though, really, is that GUI development can be a PITA and if you get a decent editor such as Jigloo, you can get stuff to look 85% right without having to do a lot of layout math.
Incidentally, I didn't actually expect you to respond ;). I think I even hit the problem you describe, of creating (in my case a generic template) dialog. The content pane where the message or business widget or whatever would show was always cut off by the button pane, despite doing essentially what you did.
I'd actually like to do some Linux desktop development, but my expertise is in Java and as an Eclipse fanboy, I'm pretty much committed to SWT for the near future.
Self modifying code takes a performance hit on modern processors because you have to flush the instruction cache.
Additionaly, you can get a somewhat similar feature in Java by compiling and loading code at runtime (not trivial with C++)
The fact that Carmack isn't writing Doom 3 in Java probably means that his tools are better for what he wants to do, not that Java is slow. Additionally, how many games dev tools and pipelines are written in Java? None, it's only an option now (it has been too slow before) and so it's new on the block when C/C++ have long established tool sets and libraries for them. Noone will throw away their investment in tools for a new language unless it offers significant advantages over what they already use - which Java probably doesn't do, even if it has similar performance.
You say proper design-time optimisation is better than compile-time optimisation. This is true, but it is just as true for Java as it is for C++. Smart java code is faster than dumb java code just as the same holds for C++.
Digital did a similar thing with the FX/32! x86 emulator/translator, which would let you run Windows NT/x86 programs on NT/Alpha. (A similar program existed for Linux as well.)
As you ran the application, it would cache the Alpha-native code generated by the emulator, and save the parts that seemed consistent between runs.
It was especially nice with NT Terminal Server on Alphas, where multiple users running the same x86 program would actually see a speedup after the first person started up.
(FX/32! was a PITA to apply to Terminal services apps but I managed to get it working eventually...)
Once again, static compile-time optimizations cannot match run-time optimizations unless the compile-time optimization is to write out every possible code-path that is most optimal for the entire input space. Now, you could write your program such that it analyzes its own runtime state and switches code paths while running -- but that is no the compiler making the optimization. And, at that point, you may say it is human-optimized, so it's better...
But then you might as well also point out that human-optimized C code can beat out C-compiler-optimized C code.
FWIW, I've heard arguments that even that isn't true because humans are extremly biased and a computer can just see things for what they are in terms of bits and bytes without getting distracted by our human abstractions.
Uh, no. Java != JVM.
Did you see a definition for Java somewhere in the benchmark writeup? Certianly Java is not in its entirety defined by the JVM, but the casual term "Java" is an unbrella term that certainly includes a JVM.
This lack of an explicit definition is one of the problems with the banchmark. Did he mean the language? The standard libraries? The VM? The version or vendor-specific implementation so of the standard libraries or VM?
Have you never heard of self modifying code? Look it up. You can do it in c++. You cannot do it in Java. Could you be more specific? I mean, having a code path that chooses replaces part of its functionality could be termed "self-modifying code". You can infact do that in Java with the Functor pattern. If you mean actually modifying discrete portions of logic without the aid of virtual functions that can be replaced, then wouldn't that be exactly what the HotSpot is doing? Now, perhaps you can't do that in the Java language. But, can you do it in JVM bytecodes (other languages can be compiled to JVM bytecode)?
With c++, you can take advantage of architecture specific optimizations
You have that in Java as well. The JVM, being part of Java, is certainly allowed to be written differently for different architectures -- and the HotSpot VMs by extension can re-arrange the machine code it JIT'ed to be more optimal for the hardware at hand.
Furthermore, the specific optimizations you name could be implemented in c++. The compiler won't do it for you, but a clever enough developer could do them
This is teh same argument ASM programmers used against higher-level languages, and the same argument C programmers made against C++. If you're such a hard-core hand-optimizing code freak, by not write your code in your favorite hex editor as the actual machine instructions. This is what the authors of Comanche Maximum Overkill did years ago (sorry, it's so old My point is that proper design-time optimization is going to be better than compile-time optimization no matter what. No algorithm can yet approach the intelligence of a human when it comes to optimizing.
I disagree. Runtime optimizations are basedon the actual state of a running system, nto a developer's pre-conveived notion of what it will encounter. Profiling can get you part of that, but only if you profile for every possible input. Have you never sat down and watched a user use your program and realize, "hey, that user is using it in a way it wasn't designed for!". Runtime optimizations could handle that, but for all of the intelligence of a human, we're biased, short-sighted and emotional (just look at some of the posts in this thread!)
The whole point of java is to remove you, the developer, from the architecture.
Yes, you're right! Well, no you're not becuase that's not the whole point of Java. But the underlying point is still true.
With Java, you let the friggin machine do the work of optmizing it for where you're deploying. As we've seen elsewhere in this thread, you can use special nitty-gritty flags on C++ compilers to target certain architectures. But how often do you do to a page to download binaries and see one compiled for your exact stepping model of the Pentium III? You just don't. Sure, open source has the advantage that you can get teh source and compile it for your hardware, but that does not help the rest of the non-geek world. Maybe if machines saw a *.c file and when you double-clicked it, it automatically compiled it specifically for your machine and exeucted it users would adopt that. But even then, the statically-compiled binary will not have runtime optimizations unless it is hand-coded in. That takes me back to my earlier point that if you want to sit in the dark corners writing tight device drivers in machine code, go ahead -- but the rest of us need to get paid at jhobs where performance is measuredn ot just in how fast your application runs, but in how long it takes to get it done. And while you're may be 3% faster, mine will be developede in 3% of the time that yours was.
Once again, static compile-time optimizations cannot match run-time optimizations unless the compile-time optimization is to write out every possible code-path that is most optimal for the entire input space.
I realize this. Grandparent didn't acknowledge that every possible optimization that a JVM performs is inherently available to lower-level languages also (even if it's not convenient, or idiomatic) with his silly "Fact:" spiel. What bothered me more was his resort to pedantry and his attitude.
What bothered me more was his resort to pedantry and his attitude.
Agreed. Sometimes, though, I'm just as guilty. I love Java. And I'ma guy who went BASIC->C->ASM->C++->Java (with some unimportant tangents along the way). I'm not saying it's 100% better than C++ either. The part I get emotional about is the absolutists who can't believe Java could ever be better than C++ in any way. Unfortunately, the benchmark which started this thread -- while done with good intentions -- does nothing to further Java's cause.
I use SWT. Much faster and native look and all that.
SWT is one I haven't fiddled with yet. I'm sure I will eventually, but for work everything we have is in Swing and for fun I prefer to write Qt.
I'm familiar with working with a new GUI toolkit.
I've used Swing, GTK, Qt, AWT, MFC, Win32, ObjectWindows, Liant C++ Views, zApp, the NeXT Devkit, TurboVision, and two UI toolkits I wrote myself (one for DOS-based graphical applications and one for a small proprietary operating system). There may be one or two that I've forgotten, as well.
Out of all of those I only hated MFC and raw Win32. GTK, Swing, AWT and zApp all fall into the category of "usable". I liked OWL, Liant, TurboVision and both of my toolkits (though they were clearly inferior, functionally). Qt and the NeXT Devkit are the only tools I found fun to use, though Qt is still well below the NeXT stuff, at least to my biased recollection.
I'd actually like to do some Linux desktop development, but my expertise is in Java and as an Eclipse fanboy, I'm pretty much committed to SWT for the near future.
I'm sure SWT is perfectly serviceable, and Eclipse is an excellent tool.
Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
It's the first time an AC trumped me.
You win this time, Batman!
Damn meddling kids.
I think it is not the intention of the bench mark to make the languages run in the exact same manor. I think the bench mark would be much more useful if it exploited all the features of each language, and then measured how fast it accomplished the task. The fact that Java uses a gc system where as C++ forces the programmer to keep tighter track of memory usage doesn't mean Java is cheating. That is the design of the language. If the intent of the application is to occupy as small a memory foot print as possible - then C++ has some advantages.
Forcing Java to behave like C++ or C++ to behave like java doesn't really have much to do with the bench marks.
Now poorly written code in either language would make the bench marks more susceptible to criticism.
-- As soon as I have an interesting sig, you'll be among the first to know!
The halting problem is not an algorithm - it can be proven that any "solution" will always have the possibility of non-termination.
An algorithm runs within a finite amount of time.
- With c++, you can take advantage of architecture specific optimizations
You have that in Java as well. The JVM, being part of Java, is certainly allowed to be written differently for different architectures -- and the HotSpot VMs by extension can re-arrange the machine code it JIT'ed to be more optimal for the hardware at hand.You replied with a non-sequitur. What I said is that in c++, you, the developer can take advantage of the hardware. What you replied with is that the JVM can take advantage of the native hardware too. Don't you see how those two things are not equivalent?
With Java, you let the friggin machine do the work of optmizing it for where you're deploying.
Yes, and that's great, and it's well suited to certain tasks. However, a general purpose run-time profiler/optimizer is not going to outperform a proficient human. When you absolutely need to count every clock cycle, like if you were writing Doom 3, f'rinstance, you simply can't rely on a smart JIT compiler. The profiling itself is a performance hit. If you knew enough about to Java architecture to implement your algorithm in the most optimal way from the start, the profiler would slow down the run-time.
With c++, you can examine the native code, and if the compiler does something stupid, you can drop down into assembly and get your hands dirty removing pipeline stalls, making sure your inner loop fits in the cache, and other stuff that you just have to hope the JVM will do for you if you are a java programmer. If the JVM does the wrong thing, you're stuck.
I'm not trying to knock what is obviously a highly favored language of yours; believe it or not I've written some Java myself, and I'm not a language bigot. I'm just saying, use it for what it's intended to do. Fastest performance isn't it. Reasonable performance with good cross platform compatibility is the best you can hope for, and all it was ever intended for.
WWJD? JWRTFA!
The "do" and "named let" syntaxes are called "library syntax" in R5RS because they are defined in terms of truly primitive syntax like procedure calls and lambda. Since Scheme's syntax is extensible, it needs a very small amount of truly primitive syntax.
what
Yeah, and I must admit guilt for stirring up the pot a bit. Looking back at my original post, it seems like that was what I was saying, even though it wasn't what I was saying.
Naive java can definitely be faster than essentially the same code in c++. That's a fact, and I don't think anyone is disputing it. The author (troll?) of the /. story just pushed my buttons with his terminology. His idea of "optimized c++" was a compiler switch, and there is so much more to optimizing than that, it just is not funny. I wonder if he knows what a pipeline stall is? My guess is no, given the sorry state of his "optimized" code (well covered by others in this thread).
WWJD? JWRTFA!
Java never sold itself as the fasted gun in the west.
And of course you'll write Java to take advantage of HotSpot and the GC running when it needs to. Why?... because for the time being (up until the GC turns over) you end up with an app that can rub noses with C++. This article does prove that.
You need to add all the other great features of Java... the most important being that it's a very pragmatic system to code in (no need to explicitly free memory etc etc), Java is a fantastic thing.
The fact that it can HotSpot and have parts of an application go toe to toe with C++... it makes me a truly happy Java programmer.
It's another topic, but people also deny its cross platform nature, but it does deliver on this promise. I needed to quickly run a complex IDE (IntelliJ's IDEA) on a linux box, but no Linux version of it. By simply copying the Jars from a windows box and starting it up, it was usable without a problem.
Personally, Java's the bomb!
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.
Whoah, there. This was right...a number of years ago. GTK and Qt have neatly reversed this. It's much more of a pain in the ass to do, say, a Win32 GUI than it is a GTK or Qt GUI.
May we never see th
Swing faster than Gtk? Maybe in some fantasy universe. Gtk isn't even overly efficient, but suggesting Swing is faster is just insane.
That's why I studied three times more Prolog than LISP ;)
Don't you see how those two things are not equivalent?
Yes.
However, a general purpose run-time profiler/optimizer is not going to outperform a proficient human.
This is one point we'll continue to disagree on. The theory behind runtime optimizations is that there are some things you can' know ahead of time or some conditions that simply aren't static. Again, a "human" could hand-code his application to do runtime proofiling and choose diferrent predefined code-paths based on that... is that what you meant -- essentially building in a runtime optimizer?
With c++, you can examine the native code, and if the compiler does something stupid, you can drop down into assembly and get your hands dirty removing pipeline stalls, making sure your inner loop fits in the cache, and other stuff that you just have to hope the JVM will do for you if you are a java programmer
You do have an intermediate option. You can disassemble the classfile (standard JDKs come with the tool named 'javap' for this), look at the JVM Instructions and see if they are doing something stupid. Some crazy minded folk have hand-coded Java machien instructions and built *.class files themselves. There are also a handful of other languages you can compile ot the JVM which may give you more control over what you are doing.
But, that's not controlling it in Java. In that case, you stil have an option. There are times when I've decompield a Java class file, looked at the JVM instructions it used, and realized if I coded my Java program diferently, the compiler would generate different instructions that would be fewer and faster.
Fastest performance isn't it.
I still have a faith that Java will be faster than C++ in some cases. The fact that this benchmark was flawed doesn't mean it isn't true. I certainly don't believe it to be true ubiquitously for all cases. BUt blanket statements like "Fastest performance it isn't" are just too absolute for be to pay attention to.
Two questions:
1- Which GUI toolkit did you use for the C++ application?
2- Which GUI toolkit did you use for the Java implementation?
Had you given any thoughts of using a modern C++ toolkit for the re-implementation?
I wouldn't you expect you to understand. Now go along and play with your Linux computer, newb.
You need to work on your compsci fundamentals. Many problems involving source code transformation reduce to the halting problem. The question that the compiler is asking in a general case destructive-recursive-to-destructive-iterative is, "Are these two programs equivalent?" This is clearly a case of the halting problem.
In practice, these kinds of optimizations can be pulled off in special case scenarios because the optimizer knows, a priori, about them. I would not be surprised if Sun's optimizer programmers threw this one in, maybe as a proof of concept or maybe for fun.
In theory, the only way you can really do this kind of transformation reliably is to make your program very simple. One of the reasons that functional languages like removing destructive operations and enforcing stateless functions is that it makes these kinds of optimizations easy.
Scheme for example, enforces optimization of tail-recursion to a loop. This is a hard problem in general, but Scheme's design has the consequence of making the optimization practical to do consistently.
Common Lisp. on the other hand, doesn't have such a simple basic structure and as such can't promise things like this.
Slashdot. It's Not For Common Sense
Just FYI, using a GC with C++, changed the benchmark to:
c++: 14.66user 0.02system 0:15.14elapsed 97%CPU
java-server: 17.60user 0.62system 0:18.84elapsed 96%CPU
And, there is still significant room for improvement in the C++ implementation. I see that some have even done GC work which specifically targets transient object creation and destruction. My point being, there is nothing but up for the C++ objinst benchmark. Other prospects would be to simply look at other heap managers as well as simply writing a custom heap manager specifically targeting these transient benchmarks which would reduce the number of deletes to two or three (versus 200,000,000) and completely avoid the overhead of object destruction (currently, 200,000,000). This final solution, I believe, would put it on par (implementation wise) with what the JVM is doing. But, even without an apples to apples comparison, C++ is already taking the lead.
Thus far, I have submitted back four improved benchmarks back to the tester. All that I have submitted back, have been faster than the java implementation. Oddly enough, while attempting to create some additional benchmark runs which would help further remove noise, I started running into some serious problems with java. Bluntly, some of the benchmarks can not be run with java because java runs out of memory on my system (I only have 512M). Even after increasing java's memory up to the ceiling of my free ram, java is unable to complete the benchmark, having run out of memory. In one such test, the c++ code finished in 1.99s while the java code ran out of memory after 6+s. Worse, the c++ code used about 50+M of ram while the java code ran out while attempting to use 380M. Oddly enough, the more work you asked of java, the worse java seemed to do. In my additonal tests of the strcat benchmark, performance tilted toward C++ ranging from 29% to over 300%, depending on the amount of data being processed and which JVM options were being used.
I realize this is a pretty poor apology for Swing, but the fact is I've found it to be basically ok, well documented, and the Web is riddled with example code if there's something particularly knotty (or unintuitive) to work out. I can, however, appreciate the pleasure of working with well crafted tools (as I suggested in the other post, the Eclipse IDE is my current favorite scalpel), so even though I'm basically a Gnome guy, based yours and the sibling's posts recommendation, I'll take a crack at this Qt stuff ;).
I used the Visual Age for Java layout tools. I actually don't think that they generated bad code at all. In fact it was pretty good code. I haven't used the WASD layout tool as much so I don't know about its generated code. In any case the layout tool is great for something that doesn't need to be flexible and doesn't need to resize or work at different resolutions. Otherwise you have to do layouts by hand. The basic layouts are easy to understand but look like crap. To produce a really professional looking layout takes a lot of effort and tweaking with Swing. I wish it was easier.
Lasers Controlled Games!
You never used PowerPlant? That was sweet.
Lasers Controlled Games!
You should really post questions non-AC, as otherwise people can't see you responded... it was only by chance I even saw your message.
Anyway, the best profilers are things like OptimizeIt (built into JBuilder now) but that's pretty expensive - worth getting a licence for a business.
The cheap way is to use the -Hprof flags that are there in every JVM. You can have it dump profile data for method times, and even better dump memory profile information which can help detect "stuck" objects (objects that are never collected because you still have a reference to them). I used to use a tool called "HAT" to analyse the results but I'm not sure that's been updated.
If you're doing J2EE work you can look at a book called "J2EE Performance Tuning". For general tuning (like apps) I'm not really sure what a good book would be, but look around the web for "Java Profiling" and you can find a lot of good material including some cool free tools.
"There is more worth loving than we have strength to love." - Brian Jay Stanley
Or, if you're not a developer, can't write code to save your life and really aren't qualified to comment on an article about programming language performance, please say so.
No, bother, I was right, the article was a troll. The Java server is impressively fast, but C is still faster for most purposes.
Friends don't help friends install M$ junk.
"once"? I'll take that to mean "a few years ago".
Try this experiment again, but with GCC 3's g++. I think you'll be pleasantly surprised.
with wxWidgets than in Java.
I've used java and wxWidgets, and C++ just rocks with the right libraries around.
Java has some nice points, like serialization, but in overall, C++ wins, if you know what to use.
We are Turing O-Machines. The Oracle is out there.
I agree with you about VB, and this is exactly my point: low learning curve because of simplistic widget concepts != ease of use != better code.
Examples: Qt is not MVC, take a label or a tree - they don't have data models. Why do I have to use setText on a QLabel, I should be able to just provide something that implements TextModel and let it take care of the text change notifications. The visual and data aspects are very intermixed. I hope I don't have to explain why this is bad. Some people call that a feature and call abstraction "bloat".
notification mechanism: Last time I checked, QT was using a custom prepocessor for the notification mechanism. I've had many problems in the early days because of more advanced C++ construsts not being compatible. And using C++'s limited features as an excuse doesn't work anymore, check what the Modern C++ design book / Loki library. Even trivial techniques as partial template specialization can help a lot.
Flexibility: It lacks interfaces. In order to change a behavior sometimes you have to reimplement the entire widget, or at least inherit from the widget. The widget classes are too big, they are doing too many things that they are not supposed to. C++ doesn't have interfaces, but I use classes with only pure virtual functions except the virtual destructor.
A better GUI toolkit? Swing is one, even maybe JFace. In the C++ world maybe none, I have to give Trolltech credit for being the only ones doing something about the C++ GUI situation. The my GUIisBetterThanMFC argument frankly is not enough.
I had to buy 5 licenses for a total over 15K. How is that reasonably priced for just a GUI library? In most of the cases you get an complete environment + gui toolkit for free (Eclipse) or a complete environment + gui tookit for less than half the price (M$).
Well, it is. Try the latest versions of Java (1.4.2 or 1.5) and you'll notice how much more responsive the app is. Note that JDK 1.5 uses OpenGL for Java2D rendering which makes it a hell of a lot faster.
In C++, isn't using const a hint to the compiler that the programmer doesn't expect the value to change. For example:
const char * p // The data pointed to is constant
int * const p // The pointer must always point to the same address
const int i = x*y; // i cannot change it's value
I am really curious if the use of const could help the situation you describe.
const double x=5;
double *p = &x;
But really, the question here is whether a generic run-time profiling algorithm can outperform a human with time on his (or her) hands and a good profiler.
No, it isn't. Not really. Well, at least unless you want to limit the test to this kind of stupid benchmarks instead of real-world situations.
The question is whether there are enough humans proficient in optimizing that have time on their hands.
To which answer is obviously NO.