Is "new" expensive in java?
java
Solution
Memory allocation is vastly different between these languages; this a big subject and it cannot be reduced to a simplistic question like whether `new` in java works "in a similar fashion" as in C++.
To give you a simplistic answer, it certainly does not work in a similar fashion because in Java you never need to `delete`.
To make you happier, let me also add that `new` in Java is purported to be a lot faster than in C++, because the runtime does not need to maintain linked lists of allocated and free blocks, and it does not have to search for a gap that is large enough to contain the block you need. Also, it does not suffer from the memory fragmentation problems that you may encounter with C++.
Most of the time, (if you are running under plentiful memory conditions, and in modern days we usually are,) the java runtime simply has a pointer pointing at the boundary between the allocated memory and the free memory, it takes a copy of that pointer, it adds the number of bytes that you want to the pointer, and it returns the copy to you. The overhead comes later, during garbage collection.
So, overall, java tends to give you memory quicker than C++ does, but it adds a certain overhead dispersed over your entire runtime due to frequent and complicated garbage collection. This overhead is unavoidable, and somewhat unpredictable, but on modern machines it is mostly (though not always) imperceptible.
The bottom line is that from the start, Java aimed to free programmers from having to worry about memory allocation, and to a very large extent it has been very successful in doing so. It is only under extremely rare, highly exceptional circumstances, that java programmers need to worry about pre-allocating objects, implementing their own object pools, etc. All these things are mostly non-issues in java.
Problem
I'm coming from C/C++ background, I wanted to know if "new" worked in a similar fashion as in those languages. For example, for performance gains in C++ one would allocate a large amount of memory up front and use this memory.