This is definitely a case where switching to primitive types is a
no-brainer. There are some more subtle cases (that I can't come up with an
example for) where we should tread more carefully.
Another example of this sort of issue is where we have a table of counters.
The temptation is to have a Map<String, Integer> or some such. Much better
is Map<String, MutableInteger> where we define the MutableInteger to have an
increment. Even better than that may be to use a primitive hash table such
as provided by trove.
In a recent piece of code, I saw this sort of change make nearly 10x
difference in speed.
On Fri, Aug 22, 2008 at 6:31 AM, Sean Owen <[EMAIL PROTECTED]> wrote:
> As you may know, I love my Java and am terribly picky about the
> details. You may have seen me "helpfully" tweaking the code over time
> here and I hope that's OK with everyone. I assure you it will lead to
> faster, sleeker, correct-er code.
>
> One thing I'm seeing a whole whole lot of in the code is a lot of
> boxing / unboxing overhead. Conveniently, primitives like double are
> virtually interchangeable with their object counterparts like Double
> -- Java does the conversion for you. However this leads to some
> invisible but potentially large overhead. For example I saw a loop
> like this:
>
> Double total = new Double(0.0);
> for (...) {
> Double value = new Double(someDoubleObject.doubleValue());
> total += value * value;
> }
>
> Aside from the unnecessary object allocations you see, there is at
> least one you don't -- updating total make a new object every time.
> There are two calls to doubleValue() you don't see as well. Instead:
>
> double total = 0.0;
> for (...) {
> double value = someDoubleObject.doubleValue();
> total += value * value;
> }
>
> It's not just the memory -- though on a 64-bit platform, a Double
> requires 20 bytes: 8 byte object reference, 4 byte object 'header', 8
> byte double value. The allocation takes nontrivial time, and,
> nontrivial time to GC later.
>
> I think the rules is basically -- always use a primitive unless you
> can't. You have to use objects when putting values into a Collection
> or Map. Sometimes you also want to distinguish between a value and no
> value, in which case an object reference allows for "null". Otherwise,
> it's all primitives.
>
--
ted