Java Performance Urban Legends
An anonymous reader writes "Urban legends are kind of like mind viruses; even though we know they are probably not true, we often can't resist the urge to retell them (and thus infect other gullible "hosts") because they make for such good storytelling. Most urban legends have some basis in fact, which only makes them harder to stamp out. Unfortunately, many pointers and tips about Java performance tuning are a lot like urban legends -- someone, somewhere, passes on a "tip" that has (or had) some basis in fact, but through its continued retelling, has lost what truth it once contained. This article examines some of these urban performance legends and sets the record straight."
SWT isn't platform-dependent. Look it up.
has poor start up time, and requires an absolutely massive amount of memory. That, and garbage collection makes almost-real time ("soft" real time I believe is the technical term) UIs more difficult than they should be.
Oh, good, another one to shoot down. While I don't have any numbers at all, I know that Apple 'fixed' this problem to an extent by making parts of java shared, just like any shlibs. This alleviates the 14 apps, 14 bags of shit problem to some extent.
Apple then returned the changes to SUN, who rolled them into 1.4.x.
I wish I had numbers. Sorry.
- A tax adapter that did operations for each order. Setting a load tester against the server caused the machine to max out on memory. So I eventually had to create my own pool of objects to stop them from getting touched by the garbage collector.
- Text parsing/processing that operates on each line of many megabyte files. When done with mutable String objects, it kept increasing memory as a function of time, never reducing the memory load. It's not like I kept references to these objects. I had to reprogram it to not keep allocating objects for each line.
I'm sure others have their own examples to contribute.I think he's talking about something like this:
/* snip */
while(true)
{
Object o = new Object();
o = null;
}
The GC won't free the memory in realtime (or, sometimes, ever), as would be the case for C++/C with new/delete malloc/free.
Do you even lift?
These aren't the 'roids you're looking for.
I know it's a joke (and I'd mod it up if I could) but for those that are completely clueless...
JAVA was slow about 8 years ago, when most people who would have been early adopters where making their mind up whether to adopt JAVA or not.
Those that did, did so because the programming lanugage itself included features which made the worst kinds of common mistakes in C and C++ go away. Those that didn't, didn't because JAVA suffered from problems that are common to any new language. Unfortunately the extreme media spotlight and pressure to use the new (to most at that time) techniques of OOP only made the latter group dig in their heels and avoid any acknolwedgement that JAVA has (or even could) improve.
It's the same kind of mindframe that still has our company operating at half duplex (since a network card we bought in '92 dropped packets like crazy on full)
I've worked on two embedded projects using Java on low power (energy consumption/CPU performance both) platforms. Both projects had amazingly similar things happen. I stated up from, "Java is interpreted; it will be slower than the C code of the previous project on the platform, potentially significant."
The reply, "We don't care about performance."
Four months later... "Why the hell is your code so slow?"
Interpreted is as interpreted does.
I used to wonder what was so holy about a silent night, now I have a child.
While MySQL has transactions, it does not have ANSI standard transactions. They are implemented using a non-standard syntax and they don't follow the standard behavior rules.
ANSI SQL:
BEGIN TRANSACTION;
BEGIN TRANSACTION;
DELETE FROM Table1;
COMMIT TRANSACTION;
ROLLBACK TRANSACTION;
MySQL:
BEGIN;
BEGIN;
DELETE FROM Table1;
COMMIT;
ROLLBACK;
The differences here are two fold. As you can see MySQL's syntax differs from that of normal ANSI SQL so you lose portability. Secondly MySQL permanently makes changes to the data at the first COMMIT statement so the changes can't be subsequently rolled back.
In ANSI SQL no changes would have been applied to the data after this batch completed. In MySQL your data would be gone.
Another point in this is MySQL's handling of corruption. It is mentioned that if you perform a full backup and keep the binary logging turned on that you can restore from the backup and replay the activity of the day. Apart from being a manual task it can be a lengthy task. Other databases simply restore themselves to the last known good state. In both cases some data will be lost, but at least in the latter case sleep wont be lost from a phone call at 4:00 AM.
In a real project, using JDK 1.3 on various platforms, we had performance issues. So, we measured speed in various ways, and found three main problems.
1: Synchronization.
This is slow. Really slow. And it just gets worse when you're running on dual or quad processor machines. StringBuffer is a major offender; in a lame attempt to save one object allocation, it uses a simple reference counting device which requires synchronization for operations as trivial as appending a character. Writing a simple UnsynchronizedStringBuffer gave a measurable performance boost.
2: Object creation
This is the real problem. GC is slow. GC on SMP machines is still really slow in JDK 1.3 -- maybe JDK 1.4 is better, my experience is a little out of date. By rewriting large chunks of code to create fewer objects (often by using arrays of primitives) we made it much faster -- close to twice as fast, if memory serves.
3: Immutable objects
Yes, these add to GC, and so are bad for performance. But not such a great evil, so long as you don't overuse them.
Funny that the article "debunks" these myths without figures, when our thorough measurements showed that the problems are real, and in our case would have killed our chances of meeting performance targets had we not found them and dealt with them.
Some bigger issues for server-side design: be careful how you use remote calls (such as RMI) and how you use persistence (such as JDO). But the small things, which the article seems to misrepresent, matter too.
If you wrote a program with mostly static methods, primitive types, and arrays, minimizing object creation and virtual method calls, it would run almost as fast as the equivalent C++ program. A couple years back, I implemented Sieve of Eratosthenes in C++, Java, and VB, and the speeds were comparable. IIRC, on Windows they were within 10% of each other. On Solaris, bizarrely, C++ kicked Java's ass, but Java was still only about 50% slower.
But if you write an object-oriented program, it will be slower. OOP tends to be higher-level, and thus faster to write but slower to run. All those memory allocations and virtual method calls take time, and they're difficult to optimize. Also, the standard libraries are kind of slow, because they try to be really general (e.g., synchronized collections).
I've used Java on embedded applications, on systems that create lots, and lots of objects. And I don't recall ever running out of memory, if there wasn't a bug in the Java program.
But I'm not saying you're lying or wrong, only that a well tuned, well supported, JVM doesn't do this.
the opportunistic garbage collection of C/C++ simply leads to better performance than any language that tries to do the garbage collection for you.
What opportunistic garbage collection of C/C++? You mean delete and free? Get real! Personally, I wouldn't trust the average programmer to even collect garbage correctly more than half the time, and that doesn't cut it. I've had way, way less problems with Java GC than I've ever had with C/C++ in a realtime system. People have spent weeks finding memory leaks; and one time a leak I found was a ghastly C++ compiler bug where the compiler screwed up the automatic destructors on unnamed objects.
-WolfWithoutAClause
"Gravity is only a theory, not a fact!"Yes, if I need speed, I use C, the same as anyone else.
Not me. There are some *fast* functional programming language compilers out there. I've ported some of my log processors from python to OCaml, scheme (for the bigloo compiler) and C. The OCaml and bigloo compiled versions were almost exactly the same speed, and only slightly slower than the C version. The C version took me a *LOT* longer to write due to the difficulty of expressing what I was trying to do in C and making sure it was doing it safely.
In general, I agree with you, but I make great efforts to avoid C, as I am one of those who believe that C is inappropriate for almost every task for which it's used today (even some of the ones for which I'm using it).
-- The world is watching America, and America is watching TV.
One of the reasons is that interactions with caches are hard to model, making it hard to know what to do to minimize problems. Caching is, inherently, a deal with the devil: you get speed but lose understanding. Sometimes you lose the speed too. Even when you understand, there's not much you can do. Sometimes complicated stuff is inherently expensive.
When I say caching, I mean not just CPU caches of RAM, but also RAM caches of (potentially swapped-out) process space. If you allow a naive garbage-collector to operate freely, it will happily consume the entire address space available, typically the sum of available RAM and swap space, before garbage-collecting, so the process will run not from RAM but from swap. When it garbage-collects, too, it has to walk a lot of that memory, and swap it all in.
Just running "ulimit -d" in the shell where the java (or other GC-language) program runs can help a lot. It will GC a lot more often, but if nothing is swapped out, the GC happens a lot faster, and the program's regular execution doesn't have to touch swapped-out pages. You have to know a lot about the program and the data it uses to guess the right ulimit value, and if you guess wrong the program fails, but a thousand-fold speed improvement earns a lot of forgiveness.
Did you really believe garbage collection would mean you don't have to know about memory management? It makes memory management harder, because the problem remains but there's less you can do about it. (For trivial programs it doesn't matter. If you only write trivial programs, though, you might as well find some other job.)
There's a similar effect with the CPU cache and RAM. Ideally you want the program code and the data it operates on all to live in cache, because touching the RAM takes 100 times as long at touching cache. With bytecodes, you have a lot more "cache pressure" -- you have the bytecodes themselves, the just-in-time compiler, and the native code it generates. At the same time, since your memory manager generally can't re-use memory that you just freed, it allocates other memory that, when touched, pushes out something else that was useful (such as program code).
The result is that no matter how clever the JVM is, there's not much it can do to get the performance of real programs close to optimal, or even within a pleasing fraction of equivalent C++ code. This despite all the toy benchmarks that seem to prove otherwise, and which carefully avoid all these real-world problems.
Of all the promised features of Java (like Lisp before it and C# after it), we're left with the sole remaining feature, that its virtual machine specifies precisely (or abstracts away) enough details of the runtime environment that the code is more portable than a faster native implementation, and the code might get written faster for the author having avoided thinking about details that affect performance.
The sole saving grace is that most programs don't have much need to run very fast anyway, or if they do it's hard to prove that they ought to run faster. Most people take what they get without complaining, or without complaining to anybody who cares, or without doing anything to make whoever is responsible uncomfortable enough to have to do anything differently. A whole generation trained to accept programs that crash daily or hourly is thrilled to find a program whose biggest problem is that they suspect it might be sluggish.
You can avoid a lot of these problems in many cases if you use a function like "select()" in a single-threaded program (which, IIRC, Java unfortunately doesn't support).
The standard java NIO APIs support non-blocking IO (which is what select() is).
To support this with some real numbers, a while ago I was profiling a C++ application I was writing. The application has ~200,000 lines of code, and was writing out ~3,000 values per second. This was not good enough, so I profiled, and carefully improved the "top scorers" in the profile. By changing ~200 lines (spread over a variety of classes and functions) I managed to bring the speed up to ~55,000 values per second. So that's 0.1% of the lines, and an 18 times increase in performance. That's not a bad result for one afternoon of careful coding.
Were those 200 lines so badly written in the first place? Hell, no. They were fine. But there was a potential for improvement here, and making that improvement had a discernible effect throughout the system. I could spend the rest of my life improving the rest in the same manner, but I doubt I could get another factor two out of them.
It goes without saying that without the profiler I could never have done this.
For the record, I found that there were repeated calls to strlen() in a tight inner loop. The most important thing I did was eliminating that call. Smarter buffer management did the rest. The biggest remaining bottleneck is actually in sprintf (%f) - the conversion from float to string is comparatively slow. Just generating all the values without doing that conversion gets me a speed of around 180,000 values per second.
(*) And if it hasn't, do yourself a favor and get a real development environment. Please.
The slow startup time of typical JVM's does make it feel slow and is a major annoyance. I believe at least part of the problem is that Java was originally designed to be used in a standalone enviornment instead of running on top of a general purpose operating system like *nix or Windows. When the JVM only starts once every few hours, startup time doesn't matter much. Echidna is an attempt to avoid the memory bloat and startup time of many JVM processes. I haven't tried it yet, but I probably will if I do much more with Java.
More generally, any language or runtime environment that is significantly different from that of the operating system is at a disadvantage. I wonder if any high level, dynamic, or interpreted language might benefit from a server or memory manager for the shared parts of the runtime, instead of each program having its own, independent runtime.
I know this is just feeding the trolls, but I couldnt resist:
"Trying to run java applications over X at long distances makes me want to commit suicide."
There used to be a problem with running Java on a remote X server with JDK 1.2 and 1.3, but it is fixed now in 1.4.
"Then there is the damn JVM's that each app needs..."
The new Isolation API slated for 1.5 should hopefully sort out the JVM-per-app isssue (I agree it's crap).
"For some reason the screen flickers every time you run a java app"
Again, fixed in 1.4 AFAIK.
"Humm, and cut/paste sucks, yes you can use key combos, but sometimes in windows, its nice to select all, and copy."
No quite sure what you mean here. If you mean in "Windows" (not windows) then you can select all and copy (CTRL+A & CTRL+C) in any Java text widget).
"If you cant have command line, and you must have a GUI, for gods sake use a HTML."
What??? I assume you are talking about web-based applications here? I agree, that for web applications, HTML is *usually* the way to go. However, there are some very nice standalone Java applications out there. For example (and this is not a plug, just an example), one of the best GUI CVS clients I have found is a Java application (SmartCVS).
Just my 0.02c. I've been developing Java applications for the last 7 years (since 1.1), so I think I'm entitled to an opinion....
James Bray
http://www.reeb.freeserve.co.uk
- The VM does free memory in "real-time" ( whatever that may mean )
- The amortized amount of memory is zero ( it keeps falling back to the base 94K used for the base java classes.
If you realy want to know how the VMs memory works and how to tune it, you could do worse than read the Hotspot GC Notes. Agreed that Java is not the greatest language there could be, but it is the best mainstream language for a majority of applications. BTW, this test was done on a rather obsolete PIIIthe double-checked-locking pattern is thread-safe
Bullshit.
The "Double-Checked Locking is Broken" Declaration.
It has a lengthy explanation of why it is broken in Java (because of possible reordering) and also a proposal for fixing the problem. Also see Bill's paper, in which he tells of discussions he had with Guy Steele (as in Gosling, Joy and Steele, The Java Language Specification).
Perhaps the experts can comment on this one, but isn't one correct way to implement the thread-safe singleton example in the article as such:
c hTips/1 998/tt0120.html). These 'benchmarks' are like that 'chart makers' that give you x and y percentages just to make their case look good. And in most instances, it's a specific situation that is being dealt with, which could be such a minutia element, but makes for a good razzle.
class SomeClass {
private Resource resource = null;
public synchronized Resource getResource() {
if (resource == null)
resource = new Resource();
return resource;
}
}
On immutable objects (string vs. stringBuffer)
SUN itself claims that using StringBuffer is faster (e.g.
http://developer.java.sun.com/developer/Te
I hope that the above post is part of an elaborate joke. Otherwise, looking at this and the 455 other messages comprising the debate so far, I don't think /. is about to improve its its position in the 'where to come for Java enlightenment' stakes.
1) Re: swapping. Java memory management will always be superior to that of the OS - OS constraints should never be greater than those applied by the VM. The memory limit of a Java process is defined with the -Xmx=nnn parameter. For production use, this should never be more than the physical memory actually available to the Java process.
2) Re: CPU cache: By the time a CPU executes compiled code, bytecodes are nowhere near the CPU cache (they were never near the instruction cache). The fact that the code was earlier produced from bytecodes is completely irrelevant. Furthermore, bytecode compilation is persistent - compiled code is never destroyed for memory management purposes.
3) Java and C++ optimizations: by definition, a Java JIT compiler can make all the optimizations a static compiler can make, and then some. This is because: a) the bytecode is the semantic equivalent of the source, so all source optimizations can be applied; b) it additionally has access to the complete code base, not just the equivalent of a single source file and c) it has access to the dynamic characteristics of a program, such as "branch taken" metrics, meaning that potentially indefinite refinements of the program structure are possible.
For those that are true seekers after knowledge, I think it is safe to say that your reading time will be better spent with Sun's papers on GC or VM design, starting here, and perhaps comparing mechanisms with those of LISP machines, Dotnet or the Parrot VM.
I also recommend getting up to speed with the new I/O, printing and regexp features found in 1.4 - a good start is Travis's JDK 1.4 tutorial, though it does not cover everything new.
.
An online Starcraft RPG? Only at
In Soviet Russia, all your us are belong to base!
Karma: redundant
Here are the results I found, the code is below:
First test, method1 is not final
Running method1() TIME: 4577
Running method2() TIME: 4596
Running method2() TIME: 4637
Running method1() TIME: 4547
Running method1() TIME: 4547
Running method2() TIME: 4566
public static void method1() AVERAGE: 4557
public static final void method2() AVERAGE: 4599.66
Second test, method1 is now final
Running method1() TIME: 4557
Running method2() TIME: 4576
Running method2() TIME: 4537
Running method1() TIME: 4597
Running method1() TIME: 4636
Running method2() TIME: 4557
public static final void method1() AVERAGE: 4596.66
public static void method1() AVERAGE: 4556.66
Here is the code I used. Its ugly, but I did it the way I did to best mitigate the effects of the JVM optimizing the code:
Online Starcraft RPG? At
Dietary fiber is like asynchronous IO-- Non-blocking!
Java has some brilliant profilers. JProbe is the one I use, but I hear that OptimizeIt is good as well.