Hi ive been reading up on java and found some benefits over using it that c++ like automatic garbage collection and memeory allocation, but also found java programs are alot slower then the programe being developed in c++
Is the reason for this because of the memory allocation? can someone clear this up for me?
and where is java language best used? networking but why?
thanks

Original post by shamyHi ive been reading up on java and fbut also found java programs are alot slower then the programe being developed in c++

To say that you've found Java programs to be slower implies that you've tested them yourself. What I think you are saying is that you've read that they are slower, which means your information is coming from old or misinformed sources. Early versions of Java interpreted the byte code at runtime. So, yes, they were slow. For a while now, though, Sun's JVM has been able to compile the code at runtime. Unfortunately, many people who do not use Java, or haven't used in years, are happy to go around and with complete confidence tell people it's slow today. Anyone who bothers to check for themselves will know otherwise.

When a Java app is first launched, the byte code is run in interpreted mode for several iterations. In the background, the JVM analyzes the code that is being executed and compiles "hot spots" (the modern JVM is also known as Hotspot compiler). These compiled sections of code are no longer interpreted, but executed much the same way as a compiled C++ app. The JVM has the benefit of being able to optimize the compiled segments to the user's hardware. Statically compiled languages, such as C++, must have optimizations configured at compile time. When shipping a game, for example, it is usually compiled with optimizations for the lowest common denominator. In practice, that's good enough and all is well. But Java is able to get more customized optimizations because it can detect the hardware are runtime, before compiling the hot spots. And if the user upgrades his CPU, future JVMs that support it will be able to take advantage of its new features, meaning the developer gets a free performance boost.

Additionally, each new release of Java optimizes the standard API internals, the garbage collectors (there are more than one to choose from so that you can tune your app for optimal performance), and the JVM. All of these together usually equate to a performance boost for existing apps and, of course for new ones.

Quote:

Is the reason for this because of the memory allocation? can someone clear this up for me?

Java memory allocation is actually more efficient than that of C++. There's been a lot of documentation written about this. I don't have the links handy right now, but there are several articles at IBM developer works which discuss Java topics like memory management and performance myths.

To be sure, there is a lot going on behind the scenes. From array bounds checking to garbage collection, Java's safety and security features are not free. Still, many of the features Java provides out of the box are implemented manually in robust C++ applications anyway (and often turned off in production code for 'performance reasons', defeating the purpose).

So since its early days, Java has greatly closed the gap in performance differences with statically compiled native code. Considering the amount of overhead involved (constant analysis by the runtime compiler, safety & security features, garbage collection, etc...), it's hard to believe that Java programs can perform well at all. But they really can. Still, it's quite possible (as with any language) to structure a Java program such that it performs poorly. This can happen when you don't understand the basics of Java memory management, or when you bring C++ idioms into Java applications. Benchmarks by C++ programmers are notorious for this. They almost always benchmark the interpreted phase of execution, before the JVM has had a chance to complete its analysis and compile the code.

Quote:

and where is java language best used? networking but why?

Java shines in networking partly because it was built for it. There are two networking APIs in the standard library, one dead easy to use but with scalability limitations, another that is highly scalable but a bit more complex to use. Java's built-in thread handling, coupled with the java.util.concurrent API make implementing multi-threaded applications a breeze compared to C++ (though you still need to know what you are doing, it's easier to pick up). Server applications will almost always require some amount of multi-threading.

But you can also use Java for 3D games, desktop applications, and a host of other application types (it might not be the best language with which to create an operating system, but that didn't stop people from making one.

Since this is a game development community, you might want to check out the JMonkeyEngine. It's currently being used by NCSoft on an as-yet-unannounced project. Check out the screen shots page to see other Java games being developed with the engine (the MMOG called Spirits and the hockey game on that page are both quite impressive).

So to sum up, the last thing you need to worry about with modern Java is performance. The latest version has shown huge performance gains over the previous. But that brings up the biggest problems you have to worry about: JRE market penetration and the distribution of your app.

To cover the broadest market possible and still get decent performance, you'd be safest using Java 1.4.2. That means you don't get the benefits of the features introduced in 1.5, nor the performance enhancements that came with the restructuring of the byte code layout in 1.6. However, any users running the latest version will still see performance benefits over raw 1.4. On Windows, you could bundle the JRE with your app, but that increases download size and may not be appropriate for small games (however, since Java is GPLed now, the door is open for shipping with stripped down JREs). On Mac, you have no choice but to use whichever version the user has installed. Java 1.5 only runs on versions of Mac OS X 10.3 (or was it 10.2?) and later. I'm not sure if the final of 1.6 has been released on Mac yet or not, but it will further restrict the versions of Mac OS X available.

Anyway, these are both solved problems. Several indies are developing and shipping Java games (check out ThreeRings, PuppyGames, and Oddlabs as examples). There are other little nitpicks to be concerned with, particularly for people who have a background in C++ and can't seem to "think in Java", but none of them should be deal breakers. And just to make sure you get the point, Java performance is only a problem for people who don't use Java. People who do use it for game development understand that Java is not slow and will usually exceed your performance goals.

Automatic garbage collection counts as both an advantage and disadvantage. It can be a disadvantage because you don't get any features for free- it costs extra processor time and extra memory.

In terms of raw speed- I know that Java can in theory be faster than C++ because they do lots of optimizations that C++ can't do. I don't think the reality has caught up to this theory yet, maybe some day it will.

Another disadvantage is the restrictiveness of the language. Some people find it annoying that you can't use macros, operator overloading, define multiple classes per file, have files with different names than their classes, or stuff like that. Java has many rules that make writing code kind of a pain. (Although you could also consider all these rules an advantage- they generally make the code better and easier to maintain)

The fact that not everyone has Java installed is a disadvantage, it means they need to complete a second download to run your java app (it's a ~13mb install I think).

In my opinion the biggest disadvantage is the lack of widespread adoption in the developer world. For any given problem, you can usually find a much better selection of available libraries for C++ than for Java. For example, if you want a free open-source 3d graphics library with lots of features, there are many popular ones for C++ (OGRE, CrystalSpace, Delta3d, Panda3d...). For Java there's only 1 (jME).

The most disadvantage of java for me is that you cannot create objects "on the stack". The stack is the fastest memory allocator and GC available on all platforms and languages. It's a shame the java ignores this fact.So all objects that are only needed within a method-scope per example need to be garbage collected. Placing such objects on the stack like in C++ would unburden the GC dramatically and also increase performance a lot.

Another drawback is the lack of operator overloading. Especially when deadling with highly mathematical software like 3d games with lost of linear algebra. Defining all vector/matrix operations as operators would increase readability. Java doesn't support this because it doesn't belong to OOP.

So generally there're some cases where pure OOP sucks and hybrid-languages/paradigms may be a better choise.

Original post by Christian WeisThe most disadvantage of java for me is that you cannot create objects "on the stack". The stack is the fastest memory allocator and GC available on all platforms and languages. It's a shame the java ignores this fact.So all objects that are only needed within a method-scope per example need to be garbage collected. Placing such objects on the stack like in C++ would unburden the GC dramatically and also increase performance a lot.

Another drawback is the lack of operator overloading. Especially when deadling with highly mathematical software like 3d games with lost of linear algebra. Defining all vector/matrix operations as operators would increase readability. Java doesn't support this because it doesn't belong to OOP.

For instance a generational garbage collector can implement memory allocation basically as increasing a pointer by the requested size and returning the previous value of the pointer. This results in an allocation cost similar to a local variable in C/C++. Garbage collection and heap compaction automatically free this memory later on. Since most objects only survive for a short amount of time, only very few data needs to be copied when the heap is garbage collected. So there really is no need to store objects on the stack.

Garbage collection can also be seen as a way to delay the work needed to perform the management of memory. For applications like a word processor for instance, the work to free the memory can effectively be performed while waiting for user input, resulting in higher responsiveness when processing the user input.

In HotSpot JVMs (Sun JDK 1.2 and later), things got a lot better -- the Sun JDKs moved to a generational collector. Because a copying collector is used for the young generation, the free space in the heap is always contiguous so that allocation of a new object from the heap can be done through a simple pointer addition, as shown in Listing 1. This makes object allocation in Java applications significantly cheaper than it is in C, a possibility that many developers at first have difficulty imagining. Similarly, because copying collectors do not visit dead objects, a heap with a large number of temporary objects, which is a common situation in Java applications, costs very little to collect; simply trace and copy the live objects to a survivor space and reclaim the entire heap in one fell swoop. No free lists, no block coalescing, no compacting -- just wipe the heap clean and start over. So both allocation and deallocation costs per object went way down in JDK 1.2.

That's bull actually. What both of you probably meant to say was that memory allocation in a typical Java application has reduced costs when compared to a similar application written in C/C++. It's not that these costs are part of the languages themselves, it's part of your application's / JVM's implementation.

As an example, Sun's HotSpot JVM requires that the heap's virtual addresses are contiguous, thus allowing the JVM to allocate new objects on a previously allocated heap chunk by simply doing some pointer arithmetic - that's quite fast as you might imagine.

What people usually don't get though, is the fact that this custom memory allocation scheme could of course also be implemented in your "average" C/C++ application - after all, that's just what the JVM is at it's heart (you would have to evaluate situations where this made sense, obviously).

Original post by CelvinWhat people usually don't get though, is the fact that this custom memory allocation scheme could of course also be implemented in your "average" C/C++ application - after all, that's just what the JVM is at it's heart (you would have to evaluate situations where this made sense, obviously).

It cannot, for a very simple reason: in C++ (and, worse, C), objects cannot be relocated transparently. This means that once an object is created, it cannot be moved, which prevents you from filling up holes left by previous deallocations. This, in turn, means that you will either lose insane amounts of memory to fragmentation, or will have to include fragmentation-handling in your allocation scheme.

Java can relocate objects, which means that no fragmentation occurs, which means faster allocation.

Original post by pinacoladaIn terms of raw speed- I know that Java can in theory be faster than C++ because they do lots of optimizations that C++ can't do. I don't think the reality has caught up to this theory yet, maybe some day it will.

When making a statement like this, can you also provide the basis for this statement? I'm not saying it's right or wrong, just wondering what exact data you're basing it on.

Quote:

Original post by pinacolada For Java there's only 1 (jME).

Not quite true. There's also Xith3D and Aviatrix3D. Java3D, too, although it's pretty much obsolete from what I've seen of it. There are also Irrlicht bindings for Java. And OGRE bindings for Java. Compared to the multitude of graphics engines for C++, this is still little however.

Original post by Christian WeisThe most disadvantage of java for me is that you cannot create objects "on the stack". The stack is the fastest memory allocator and GC available on all platforms and languages. It's a shame the java ignores this fact.So all objects that are only needed within a method-scope per example need to be garbage collected. Placing such objects on the stack like in C++ would unburden the GC dramatically and also increase performance a lot.

Another drawback is the lack of operator overloading. Especially when deadling with highly mathematical software like 3d games with lost of linear algebra. Defining all vector/matrix operations as operators would increase readability. Java doesn't support this because it doesn't belong to OOP.

...Since most objects only survive for a short amount of time, only very few data needs to be copied when the heap is garbage collected. So there really is no need to store objects on the stack.

That's the point. Most objects only survive for a short period. So why not just place them on the stack. Even if generational GCs can handle them somewhat effectively, they won't do it as good as a stack can. And please note that generational GCs are very complex and therefor hard to maintain and even harder to debug. A stack would be so pretty simple and powerfull.

Everytime two complex numbers are added there's a new object allocated that needs garbage collection. That's pure unnecessary overhead. The same problem occurs with string concatenation via "+"-operator. That's why many people use the ugly StringBuffer instead because of this issue.

Original post by shamy... java programs are alot slower then the programe being developed in c++

eesh... do we have to go over this again? C++ is faster in some cases, Java is faster in others. If you like Java use Java, if you don't, use C++ (or Python, C, VB, Delphi, COBOL, etc).

Quote:

Original post by shamyand where is java language best used?

Everywhere, of course(*).

Cheers,Brett

(* This opinion may not be relevant to the real world)

I think it is a very bad idea to push this issue down because language X happens to be your favorite language, since in reality it is a issue. I just finished porting some 2d physics code from C++ to Java and I'll have to say I am very disappointed in the pure number crunching performance of Java. With the C++ application I am able to push through 500 objects that consist of a polygon easily, whereas the Java application starts struggling heavily if the number of objects exceeds 100. Same computer, same code, different languages.

From someone's view who has been following Java for past five years Java has always been in the future. Java will be this and Java will be that and the performance WILL be greatly enhanced. The major problem, however, is that while Java has gotten faster and the library is great, it is not exactly built for game programming.

Simultaneously Sun isn't a big enough player to focus on game programmer's needs. They rely heavily on volunteer work and the small games community is excellent. Sun focuses on enterprise development and quite frankly all this talk about the great future of Java is inane drivel. It has always been that way and nothing has happened. I like the language and the library, but the performance needed for cpu heavy games just isn't there.

For the type of stuffs I'm doing... it's all the same. I don't do all that much high end stuffs either. The only disadvantage I got is not being able to fall back on the native APIs for applets. That's about it. In the long run, I found other ways to do what I want without resorting to the native system.

I suppose I've gotten really lazy with memory micro-management. That being indirectly due to me not caring about the garbage collecting since most of it's automatic and all.

There comes a point when you have to ask yourself...who cares? What does all this same ole arguing about JAVA & C++ performance really matter if you cant create game to start with?

I've seen really crappy games made by lone wolves using both C++ & JAVA. Half the time a lot of coders dont even truly know how to take advantage of speed improvements let alone know how to optimize their code correctly.

The bottom line, make a game, then make several more games and get good at the language your using. At which point you should (will) learn through experience how to not only optimize your code but actually code with your targeted enviornment in mind for best performance.

If you want to use JAVA then go for it because at the end of the day the game is only as good as it's designers and programmers.

Sorry if I was ranting...your original question was where is the JAVA language best used. If it ends up in the hands of the right person, it can do whatever you want it to damn near.

And truthfully people, most of the money of the game industry is in console games and MMOs - all of which (that make lots of money) are written at least partially in C or C++ today.

But:

1. Most of us are never going to work on those big money projects.2. Most of us will write several games between now and then.3. Almost any current technology is "good enough" for most games.4. The industry is constantly improving and changing, so 10 years from now our Direct X 3 knowledge won't be so important, and our Python / LISP / Java / whatever skills will come in handy to whatever extend WE the programmer can leverage them, based less and lesss on machine cost, and more and more on our personal abilities to turn ideas into output.5. With the rise of multi-core and higher thread counts, the industry is in a development / design paradigm shift right now. 5 years from now whatever language you are in, the ability to paralellize code well will be more important than the ability to get 100% performance from each thread. And hopefully new language constructs (or whole languages) will be built to facilitate this.6. Getting something DONE is more important than starting something the "right way" .

So code whatever interests you, in whatever language you like, that best allows you to enjoy your life, express yourself and share your visions with the world.

If your game rocks, most people will forgive you if it takes twice as much memory to run (higher level abstraction people).

If your game rocks, most people will forgive you that you spent twice as long optimizing the code as necessary (lower level code-to-the metal people).

Personally I do it all, I write in C++, C#, and ruby ... each depending on my interest and mood for the day / project.

I still don't understand why people try to force to use java in any and every situtations.Java is usually a swiss army knife... where allow many uses but only worth in just a few task (in the swiss knife is just the knife).

Java for example in games, you runs out of luck with directx cause the sdk of course you can (try) find a (slow and unstandard) wrapper around here.

And for stand alone applications... Swing is kinda funny but barely standard for Windows platform also slow.

IMHO:Java is a nice alternative where you can learn only one language and don't worry about the platform (at least in theory).

But also a projects can be done using multiples languages and architecture, optimizing the development time, the features and/or the speed.

Original post by Christian WeisThat's the point. Most objects only survive for a short period. So why not just place them on the stack. Even if generational GCs can handle them somewhat effectively, they won't do it as good as a stack can. And please note that generational GCs are very complex and therefor hard to maintain and even harder to debug. A stack would be so pretty simple and powerfull.

Actually, blindly allocating on the stack when the object only lives for the duration of a function can be quite ineffective. Consider the following C++ example:

will keep object alive for far longer than it needs to be. Even worse is a recursive function that stack allocates a temporary object before the recursive call, thus filling up the stack with temporary "dead" objects.

A GC would free these as soon as they're dead and the memory they take up is needed.

But obviously stack allocation can be a speedup when used with care. It's just that it's a burden on the programmer.

Region-based memory management may be the solution, allowing most objects to be statically memory managed with little programmer interference. I haven't read the whole article yet though. Edit: eeeek, it's even more technical than I expected. Maybe I'll wait for the Wikipedia entry ;-)

First things first, kudos to everyone for the civility in this discussion. It's great to see some real talk about this issue.

Quote:

Original post by Christian WeisSince most objects only survive for a short amount of time, only very few data needs to be copied when the heap is garbage collected. So there really is no need to store objects on the stack.

You can get around this stack problem by writing your own. In my last project I used an array stack of objects and then popping off as many as I need (I returned them to the stack myself, though you could probably write a manager to do it for you). I believe this is called using an "object pool", though I'm not entirely too sure on this one. Picking better data structures and algorithms helps get around these as well in all languages.

The thing about Java is that sometimes you might need to do things a little creatively to get around the GC, and some speed issues. When doing Java2D, I found out it was faster when using lots of translucency to throw in another buffer to render to, and then to blit that buffer to the back buffer, so in essence using triple buffering. (the following week I picked up LWJGL)

Quote:

Original post by Captain GoatseI think it is a very bad idea to push this issue down because language X happens to be your favorite language, since in reality it is a issue. I just finished porting some 2d physics code from C++ to Java and I'll have to say I am very disappointed in the pure number crunching performance of Java. With the C++ application I am able to push through 500 objects that consist of a polygon easily, whereas the Java application starts struggling heavily if the number of objects exceeds 100. Same computer, same code, different languages.

I understand what you mean about speed, but could you elaborate about how works? If you're using a lot of method calls (i.e. accessors such as "gets" for rectange widths for example), remember that all methods in Java are dynamically bound, which means things can a tad bit slower. Also, short-lived objects can be slow (though there may have been recent improvements on this).

Quote:

Original post by Captain GoatseThe major problem, however, is that while Java has gotten faster and the library is great, it is not exactly built for game programming.

I totally agree. However, there are a number of free 3rd party libraries that are good for game programming (I'm thinking LWJGL, and GTGE). Java's simple syntax made it easier for a somewhat clumsy person like me to pick up the language quickly since it doesn't suffer some nasty bizarre syntatical issues.

In short, which language you use should depend on what you're trying to do, and when you go about attacking the solution you need to play to the language's strengths (e.g. in Java you might want to go to native calls for really intensive number crunching).

Maybe someone could assemble hints about innovative solutions around some of Java's craziness?

Original post by pinacoladaIn terms of raw speed- I know that Java can in theory be faster than C++ because they do lots of optimizations that C++ can't do. I don't think the reality has caught up to this theory yet, maybe some day it will.

When making a statement like this, can you also provide the basis for this statement? I'm not saying it's right or wrong, just wondering what exact data you're basing it on.

Sure, well I guess my primary data point is my experience using large Java apps, such as Eclipse and IntelliJ IDEA. Both these editors feel sluggish when responding to user input, especially after they've been running for a while. Their C++ counterpart, Microsoft Visual Studio, always feels lightning fast.

I'm sure that the Eclipse and IntelliJ people are all expert Java programmers, so in this case it seems fair to blame the platform for the sluggishness.

On a similar topic, all this talk of performance makes me think of another Java disadvantage: writing high performance Java code requires too much Java-specific knowledge.

C++ was always designed to be no more high level than necessary. And so there's nothing going on "behind the scenes", the program does what you tell it to and doesn't do what you don't. To put it another way, an expert programmer, who doesn't actually know much about C++, can walk up to a C++ compiler and write high performance code (if his algorithms are good).

Java on the other hand, has tons of stuff going on behind the scenes. And our expert programmer (who also doesn't happen to know much about Java) can't just walk up to a Java compiler and write fast code. He needs to be an expert at Java. He needs to understand all those runtime flags for specifying the behavior of the garbage collector. He needs to understand generational garbage collection, so that he can avoid letting objects unnecessarily survive to the old generation. He needs to know to use ByteBuffers when using JNI code. And the list goes on..

To make it worse, the rules of the game keep changing. Before 1.2, Java programmers were told that allocation was slow and they should use object pools. Now object creation is fast and object pools are bad. Escape Analysis didn't exist until 1.6. Now it does exist, and programmers should write code to take advantage of it. It's a lot to keep track of!

The expertise problem is an issue, say, if I'm running a company and I'm considering doing an entire AAA game in Java. Am I going to be able to find and hire 10 to 20 expert Java programmers?

Original post by pinacoladaSure, well I guess my primary data point is my experience using large Java apps, such as Eclipse and IntelliJ IDEA. Both these editors feel sluggish when responding to user input, especially after they've been running for a while. Their C++ counterpart, Microsoft Visual Studio, always feels lightning fast.

Keep in mind that Eclipse is doing a hell of a lot more as you're typing than Visual C++. It's recompiling code on the fly.

Quote:

C++ was always designed to be no more high level than necessary. And so there's nothing going on "behind the scenes", the program does what you tell it to and doesn't do what you don't.

The hell it does. Tell me: What happens when you do dynamic_cast? If you can tell me in less than 1000 words, you're wrong.

Quote:

To put it another way, an expert programmer, who doesn't actually know much about C++, can walk up to a C++ compiler and write high performance code (if his algorithms are good).

Er, once you've explained to him when he should pass by reference and when he shouldn't, and when he should throw exceptions and when he shouldn't, and when he should use endl and when he shouldn't, and the difference between std::find and std::set::find, and when he should use std::vector instead of std::list even when he's doing a lot of middle-insertion. Oh, and don't forget to explain to him all the different common idioms for memory ownership transfer and how to recognize them and when he should use shared_ptrs and when he shouldn't.

And maybe that big ol' heap of gotchas is bigger than Java's big ol' heap of gotchas, and maybe it isn't. The bottom line is, any decently complicated programming language (and C++ is, heh, "decently complicated") will have such a heap. Throwing around a statement like "Java needs more special-purpose knowledge to obtain good performance" without real-world measurements is pulling facts out of your butt.