> Regardless, it still seems like (at least with local variables) value-on-
> stack reference-in-heap still applies, considering a boxed value type is a
> reference.
>
> There is some mention that member variables may not follow this rule,
> which isn't surprising--especially for statics--but I haven't confirmed
> that yet.

Well, for member variables there often is no "stack" where they could
live. For example in:

class C {
  S s;

  public C() {
    s = new S();
  }
}

Now, on which stack is s supposed to live in an instance of C? It
can't be allocated on the constructor's function stack, because it
would be destroyed as soon as the constructor is left. Instead, the
lifespan of s must be as long as that of the instance of C. One
efficient way to achieve this is to allocate it directly within the
memory for the C object.

With local variables, you are right. Values on the stack, reference
type instances on the heap. (Nitpicking: References are also on the
stack, only the objects they refer to are on the heap.) And when
values are boxed, they become reference type instances.

Now, getting back to the actual topic of this article. Value types can
be more efficient than reference types. This comes from the following:
- their instances can live on the stack (if you hold them in unboxed
local variables _or_ as unboxed member variables of a value type
instance which lives on the stack),
- a large number of their instances can be allocated as a contiguous
block of memory within an array,
- their instances can be directly allocated within an object instance
(as an unboxed member variable),
- their default constructors need not be run.

What exactly made Girish Jain's code run faster I can't tell without seeing it.

It's just important to know that value types do not _always_ live on
the stack in order to avoid misusing them. They can also be less
efficient than reference type if boxing and unboxing are heavily used
or if they are passed as (by-value) parameters.

Referring to what Jean-Michel said earlier: usage of the "new"
operator does not influence whether a value type instance lives on the
heap or on the stack.

Fabian

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to