Algorithms - Loop optimization

Iterator itr = dkItems1.iterator();

while (itr.hasNext()){

DKWorkQueue dk = (DKWorkQueue) itr.next();

if (!dkItems2.contains(dk)){

sb.append(dk.toString() + lineSeparator);

// out.write(dk.toString());out.newLine();

count++;

}

}

any way to do this better?

[589 byte] By [Plasmaa] at [2007-11-26 23:23:16]
# 1

Let me first rephrase your code into this

equivalent Java5 form (The compiler will actually

generate identical code):

for(DKWorkQueue dk: dkItems1) {

if (!dkItems2.contains(dk)) {

sb.append(dk.toString() + lineSeparator);

count++;

}

}

Now, first problem is the "+" operator.

It will construct a separate StringBuilder on the side,

use it, then discard it.

So you should first rewrite it as this:

for(DKWorkQueue dk: dkItems1) {

if (!dkItems2.contains(dk)) {

sb.append(dk.toString());

sb.append(lineSeparator);

count++;

}

}

Now, you cannot improve it further unless

you do something special about dkItems1 and dkItems2.

If they are just arbitrary collections, then no, you

have to do item-by-item comparison.

But otherwise, you can use a clever combination

of HashSet/HashMap to speed up the lookup,

as well as possibly avoid the duplication in the first place.

KathyMcDonnella at 2007-7-10 14:28:58 > top of Java-index,Other Topics,Algorithms...
# 2
...any way to do this better?First, define "better".
prometheuzza at 2007-7-10 14:28:58 > top of Java-index,Other Topics,Algorithms...