Skip to content
Advertisement

Boxing/unboxing costs and do boxed objects have copy on write?

From what I understand, Java has boxed (heap) and unboxed (stack) variables, and if I assign a boxed type to an unboxed type or vice-versa there is a(n) (un)boxing cost involved.

Is unboxing cheaper than allocating a new boxed object? And do boxed objects support COW if used readonly?

JavaScript

Advertisement

Answer

Wrapping types are not on the heap because they box a primitive type but because they are objects. Primitive types can live on the stack, as local variables, or on the heap, as member variables.

What happens in your example is:

  • Long l2 = cls.myLong; assigns the reference of the object behind class.myLong to l2, or in other words: l2 now references the same object as class.myLong.
  • l2 += 5; unboxes the object referenced by l2, adds 5 to the value, wraps the result in a new instance of Long and assigns the reference of that new instance to l2, or in other words: l2 now references a new object, which wraps the result.

Imagine this example code:

JavaScript

Compile it (javac Test.java) and see the bytecode (javap -c Test):

JavaScript

You can see that the addition to long1 expands to a call of longValue, the “unboxing”, and valueOf, the “boxing”. Like in your example, a new instance is created.

Is unboxing cheaper than allocating a new boxed object?

As we have seen, unboxing is more or less equivalent to calling a method. Creating a new instance includes more steps, e.g. additionally allocating memory.

And do boxed objects support COW if used readonly?

These classes are immutable so copy-on-write is what they always do.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement