Thursday, September 28, 2006

Java API whine

My pet peeve of the day: I want a new method added to array objects.
Object resize(int newSize)

Ideally this would be something like
T[] resize(int newSize)

but Java's templates don't really provide support for that that is worth it... so I'd prefer the first. While I'm complaining, I'd like Microsoft to add it to .Net as well.

Why? Because when you care about performance, ArrayList/Vector just don't cut it. I've seen some dramatic performance improvements by moving from ArrayList to object arrays. And when the value is something like 'int' which isn't an Object, you have no choice anyway. At least .Net Generics got that right. If that resize method was there I could replace code that looks like this:

... important stuff ...
... important stuff ...
if (index == array.length)
{
Foo[] temp = new Foo[index*2];
System.arraycopy(array, 0, temp, 0, index);
array = foo;
}
... important stuff ...
... important stuff ...

with this:
... important stuff ...
... important stuff ...
if (index == array.length)
array = (Foo[]) array.resize(index*2);
... important stuff ...
... important stuff ...

Some people will complain that I dropped the curly brackets, blah blah blah. That resize in only there because the builtin libraries are slow! It isn't topical to the code and hand and should be a small and insignificant as possible. That simple resize() method allow me to write it in a way that is out-of-the-way. That is how it should be.

I can dream, can't I?

3 Comments:

Blogger Jonathan Perret said...

I have two remarks :
- I have not made the move to .NET 2.0 yet (gasp!), but from what I read it sounded like List<T> would do exactly what you want, inc. performance-wise.
- VB.NET has carried over the ReDim statement from eons ago, so that your example could be written :

If index = array.Length
ReDim Preserve array(index*2)
End If

IMHO, even a single-line resize such as this is already too much code that is not topical to the code at hand. When I find code using ReDim, I actually often refactor it to use an ArrayList instead - provided it is not a "hot" area, of course. Readability prevails !

7:43 AM  
Blogger derek said...

List<> doesn't solve my issue because it still forces an extra object dereference (since the List<> is an extra object indirecting the actual Array reverence and the code). Also List<> and ArrayList<> etc typically add their own bounds check when retrieving values out of the array. Those extra ifs can really add up in tight loops.

3:32 PM  
Anonymous Anonymous said...

//... if check bound ... ok
//... then resize
objects.subList(newSize, objects.size()).clear();

9:59 AM  

Post a Comment

<< Home