This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Question about Int boxing/unboxing

2 replies
Joachim Ansorg
Joined: 2008-12-19,
User offline. Last seen 42 years 45 weeks ago.

Hi,
I was looking at Scala's way to convert scala.Int to java.lang.Integer.
I noticed that Scala calls different methods to convert an Int into an Integer
(see attached code).

Predef.int2Integer always creates a new java.lang.Integer . Couldn't it just
use BoxesRunTime.boxToInteger(Int) as well? boxToInteger caches the values
between -128 - 1024 .

Kind regards,
Joachim

For code like

def printInt(i:Int) = println(i)
def printInteger(i:java.lang.Integer) = println(i)

def main(args: Array[String]) : Unit = {
printInt(10)
printInteger(10)
}

this is the Java code (according to Jad):

public void printInteger(Integer i)
{
Predef$.MODULE$.println(i);
}

public void printInt(int i)
{
Predef$.MODULE$.println(BoxesRunTime.boxToInteger(i));
}

public void main(String args[])
{
printInt(10);
printInteger(Predef$.MODULE$.int2Integer(10));
}

odersky
Joined: 2008-07-29,
User offline. Last seen 45 weeks 6 days ago.
Re: Question about Int boxing/unboxing

On Sat, Mar 28, 2009 at 5:17 PM, Joachim Ansorg
wrote:
> Hi,
> I was looking at Scala's way to convert scala.Int to java.lang.Integer.
> I noticed that Scala calls different methods to convert an Int into an Integer
> (see attached code).
>
> Predef.int2Integer always creates a new java.lang.Integer . Couldn't it just
> use BoxesRunTime.boxToInteger(Int) as well? boxToInteger caches the values
> between -128 - 1024 .
>
I think we'll migrate both to Int.valueOf for Scala 2.8.

Cheers

ijuma
Joined: 2008-08-20,
User offline. Last seen 22 weeks 3 days ago.
Re: Question about Int boxing/unboxing

On Sat, 2009-03-28 at 18:24 +0100, martin odersky wrote:
> I think we'll migrate both to Int.valueOf for Scala 2.8.

Good to hear because HotSpot has special knowledge of these caches and
can perform a few more optimisations as a result. Would be good to do
the same for the Long case too.

A couple of references:

http://permalink.gmane.org/gmane.comp.java.openjdk.core-libs.devel/1279
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6807084

Best,
Ismael

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland