Andrew E said:
Its interesting that you wrote there are different performance characteristics
for short-lived objects between C++ and Java.
Can you expand on that, or suggest some references to read? Perhaps my C++
background is hampering me here, as I look at 'new Integer(1)' etc and cringe.
I'd like to learn more in this area.
Sure.
Obviously, Java and C++ differ in that Java is designed as a garbage
collected language, while C++ is designed with a manually managed heap.
It's a common, but very wrong, assumption that garbage collection is
something that's ADDED in Java, and that otherwise memory allocation
looks about the same. Neither language specifies the management of the
heap, but in fact, the heap looks very different in typical Java than in
typical C++.
C++ keeps a linked list of available memory for a process, and
allocating an object means starting somewhere in that list and walking
through the list to look for some available bit of memory. This is,
worst case, actually O(n) on the total number blocks of memory currently
in use by the system -- though clearly it's not quite that bad in common
practice. In return for the terrible asymptotic complexity of memory
allocation, deallocation in C++ is cheap, running in constant time.
(I'm not considering calling destructors, which obviously could run in
non-constant time, to be part of deallocation, nor do I consider
constructors as part of allocation.)
Java doesn't maintain a linked list, at least for newly allocated
objects. Instead, it just has a block of memory and keeps lopping off
more objects until it runs out. That block of memory is called the
nursery. So allocation is constant time, and with an extremely low
constant at that! Andrew Appel famously demonstrated that on processors
with auto-increment addressing modes, allocation can actually be
performed by dedicated CPU hardware with no performance cost whatsoever,
so it may actually be said to be O(0), or free. By contrast,
deallocation is more expensive; it is O(m+n), where m is the size of the
root set -- often considered to be constant -- and n is the number of
objects that will NOT be deallocated. Hence, the only cost of
allocating a small, short-lived object is that the next minor
deallocation (garbage collection) will need to happen a little sooner.
Now, clearly that allocation is not free... more frequent garbage
collections do add up. However, the impact is certainly far less than
frequently allocating and freeing small objects in C++.
--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation