- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Question about Int boxing/unboxing
Sat, 2009-03-28, 17:17
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));
}
Sat, 2009-03-28, 18:57
#2
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
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