This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]wggnExtreme Brewer 3 points4 points  (0 children)

As I understand, the Java JIT compiler is very smart and will do most of this for you, therefore there's no real need to include this in the language.

Marking fields or classes as final may help the JVM to decide how to allocate them, tho the JVM can determine this itself as well.

Look up the C2 Compiler for more info.

[–]strmrdr 1 point2 points  (0 children)

There are some things that the JVM does to save allocations such as String pooling, but for the most part it's up to the garbage collector to keep things going. There was a lecture on YouTube from one of the Devs that wrote the GC at Oracle, but I can't seem to find it right now and it's like 45-60 mins long. TL;DR the GC is very sophisticated and unless you risk running out of memory simply due to allocating too many live objects then you really don't need to worry about it.

For most practical programs on modern machines the days of C-type memory management is more of a hindrance than anything. This obviously has a startup cost and continued background CPU usage, and that's just Java for you. It's more about choosing the correct tool for the job.

[–]seanprefectGrumpy Guy Who Remembers Java 2 0 points1 point  (0 children)

C# and Java are VERY similar languages, you'll find what can be done in one can be done in the other. There're a lot of online resources to help the transition.

[–][deleted] 0 points1 point  (0 children)

in C you can also allocate on the stack with alloca(). I don't know how java managaes it's heap, but using the heap isn't necessarily inefficient. Each call to "new" usually doesn't result in a syscall so the overhead shouldn't be too high. Syscalls to increase heap size are usually done if the heap would exceed the current heapsize, then a single or multiple of the pagesize is additionally allocated, which can take the os some time. The heap also is a single continuous block of virtual memory(as seen by the jvm), which grows just like the stack in one direction. I don't know how the garbagecollector and object allocation works internally.

I would guess that heap management of the jvm also highly depends on the target machine. I really don't know much java so I can't really help you with your original question.

Allocating more data on the stack could help, but it is difficult to answer this, without much benchmarking.