Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Primitive Implementation

Java has both object, Integer, and primitive version, int, of basic types.

The primitive versions are faster/lighter/etc. so in general you should use them.

What I am wondering is why the designers of Java didn't only have the object types and use the primitive versions as optimizations behind the scenes.

So:

Integer foo(Integer alpha)
{
    Integer total = 0;
    for(Integer counter = 0; counter < alpha; counter++)
    {
        total += counter;
    }
    return total;
}

Would be compiled into code something like:

int foo(int alpha)
{
    int total = 0;
    for(int counter = 0; counter < alpha; counter++)
    {
        total += counter;
    }
    return total;
}

Essentially, this hypothetical java compiler would convert instances of Integer, Double, Float, etc into the equivalent primitive types. Only in the cases where objects were really needed (say to put the element in a container) would actual Integer objects be involved.

NOTE: the above code has used operators on Integer objects which I know isn't actually allowed. Since I'm inventing hypothetical Java compilers I'll pretend this one has special casing for Integer/Float/Double like it does for String.

like image 265
Winston Ewert Avatar asked Mar 12 '11 00:03

Winston Ewert


Video Answer


1 Answers

What I am wondering is why the designers of Java didn't only have the object types and use the primitive versions as optimizations behind the scenes.

To understand the reasons behind the Java design decisions, you need to understand the historical context in which they were made.

The strong distinction between primitive types and reference types was baked into the language design pre JDK 1.0. Prior to JDK 1.5, that's all there was: if you wanted to put integers into collections (for example), you explicitly used Integer.valueOf(int) etc.

When auto-boxing / auto-unboxing was added to the type system in JDK 1.5, it had to be done in a way that was backwards compatible. What they came up with is a good compromise ... but not what they would / could have achieved if they had started from a clean sheet.

(And the reason that they didn't / couldn't "get it right" first time ... way back in the early 1990s is probably to do with the original language scope and the time pressures they were under to get the first release out. If they had spent extra months / years trying to get it right, the chances are that the project would have been killed ... or that the marketing window would have closed.)

like image 52
Stephen C Avatar answered Oct 11 '22 02:10

Stephen C