News for hackers. Stuff that matters.
Re:LFMs and LFSPs (Michael Vanier via PG) by mynameishere on Monday July 09, 2007 @01:26PM (#33283)
for (i = 0; i < N; i++)

Odd example to use. It's always annoying to re-type the same thing over and over. But I recently went through a mountain of my Java code and replaced:

for (Object obj : list)

with

int size=list.size(); for (int index=0;index<size;index++)

I'm definitely very long suffering! It took a few hours but what you get with abstractions is a loss of control over implementation. When you use the tighter loop, the compiler turns everything (roughly) into this:

Iterator it=list.iterator(); //Which calls new ListItr(); for (it.hasNext()) { Object next=it.next();

The abstraction has to do that because it doesn't know whether the list (really, the java.util.Collection) is a LinkedList or an ArrayList or a Set. If your loop itself is in a tight loop, it isn't hard to call it millions and millions of times during program execution--which makes millions and millions of unnecessary allocations and method calls. There is a loss of performance which, at the end of the day, is more important than how much you enjoy your job.

Of course, other languages would allow you to specify an implementation for a given abstraction.

Re:LFMs and LFSPs (Michael Vanier via PG) by abstractbill on Monday July 09, 2007 @01:41PM (#33286)
The replacements were for performance reasons, and it took a few hours to do. Sounds like it might been more productive to replace only the occurrences the profiler told you were causing problems...
Re:LFMs and LFSPs (Michael Vanier via PG) by Tichy on Tuesday July 10, 2007 @05:10AM (#33448)
I don't understand: if you are sure that it is an ArrayList, why don't you use ArrayList instead of List to begin with? If you are not sure that it is an ArrayList, then you shouldn't use the for(int i = 0...) loop, because accessing each list element in a LinkedList by index would be extremely slow.

As for typing, in Eclipse you just type "for"+CTRL+Space and it completes the for loop for you.

Re:LFMs and LFSPs (Michael Vanier via PG) by pg on Monday July 09, 2007 @01:55PM (#33289)
Sounds like a case for macros.
Re:LFMs and LFSPs (Michael Vanier via PG) by tuukkah on Monday July 09, 2007 @05:12PM (#33337)
A higher-order method 'iterate' on containers would also do, and it would be more idiomatic in the languages i know.