Re: Objective-C vs. Java
Re: Objective-C vs. Java
- Subject: Re: Objective-C vs. Java
- From: Greg Sanborn <email@hidden>
- Date: Thu, 26 Jul 2001 12:37:16 -0700
At 2:17 PM -1000 7/25/01, Art Isbell wrote:
A downside to stack objects is the need to allocate a larger
stack. Objects require considerably more stack memory than
primitive types, so one runs the risk of running out of stack
memory. There is no free lunch...
C++ class objects aren't any bigger than primitive type objects,
except if there are virtual member functions, in which case they're
only another pointer bigger. For example, with Jim Correia's example,
ColorRestorer isn't any bigger then a local variable for the original
color. There's no need for virtual member functions in ColorRestorer,
so there's no extra stack space needed.
If you and the compiler make the constructor and destructor inline,
then there is a free lunch. ;)
greg
At 8:57 PM -0400 7/25/01, Jim Correia wrote:
Almost equivalent is not good enough for the kind of objects I think
Mike is talking about.
Suppose you have a class called ColorRestorer.
The constructor remembers the existing color, and sets the color to the
new value. The destructor sets the color to the saved color.
In C++
function_one()
{
ColorRestorer saveAndRestoreColor(red);
draw_a_string(); // draws in red
function_two();
draw_a_string(); // draws in red
}
function_two()
{
ColorRestorer saveAndRestoreColor(blue);
draw_a_string(); // draws in blue
}
In objective-c with autoreleased objects
function_one()
{
ColorRestorer *saveAndRestoreColor = [[ColorRestorer
initAndSetToColor: red] autorelease];
draw_a_string(); // draws in red
function_two();
draw_a_string(); // draws in blue because both auto-released objects
do their work in the dealloc method, which won't be called until later
}
function_two()
{
ColorRestorer *saveAndRestoreColor = [[ColorRestorer
initAndSetToColor: blue] autorelease];
draw_a_string(); // draws in blue
}
I'm new to objective-C, so there may be a way to do this. But your one
liner utility object to save the state and restore it when it goes out
of scope has to become a manual release in objective-c unless I've
missed something.
ColorRestorer *saveAndRestoreColor = [ColorRestorer initAndSetToColor:
blue];
draw_a_string();
[saveAndRestoreColor release];
It isn't the end of the world, but removes the convenience of the stack
based utility objects such that for the simplest cases, they probably
aren't even worth having.
For things where you just want the resources that you've allocated to be
cleaned up, and the next time through the event loop is soon enough, and
you don't care about the order of destruction, or whether it happens as
the stack is unwound, autorelease is quite nice when used in appropriate
situations.
Jim