I would expect your premise is correct - that int (or Integer)
comparisons will be more effcient than String comparisons. If you
have many strings to compare, the best plan is to use a
java.util.HashMap for storing them and resolving them - each lookup
takes time in proportion to the length of the string you're looking
up. Then again, my experience has been that we rarely have a situation
such that the time spent comparing strings becomes significant.
Premature optimization can bite you in the foot. Run your code
through a profiler (I've had good luck with OptimizeIt!) to see where
it's spending its time before spending your time on making it faster.
A HashMap implementation of your doSomething(String s) method might
look like this:
public interface Z {
public void do();
}
public class A implements Z {
public void do() {
// whatever
}
}
public class B implements Z {
public void do() {
// whatever
}
}
public class Punt implements Z {
public void do() {
// whatever
}
}
public class Main {
static final HashMap map=new HashMap();
static final Z punt=new Punt();
public static void main(String argv[]) {
map.put("some thing",new A());
map.put("another thing", new B());
Z z=map.get(argv[0]);
}
public void doSomething(String s) {
Z action=(Z)map.get(s);
if (action==null) {
action=punt;
}
action.do();
}
}
Jim
On Sat, 06 Nov 2004 15:41:22 -0500, Richard O. Hammer
<[EMAIL PROTECTED]> wrote:
> In the Java code I am looking at these days (JMX for example) I am
> seeing many places where branches are made based upon String equality.
> For example:
>
> void doSomething(String s){
> if (s.equals("some thing"))
> doA();
> else if (s.equals("another thing"))
> doB();
> else
> punt();
> }
>
> Compare that with:
>
> void doSomething(int i){
> if (i == 0)
> doA();
> else if (i == 1)
> doB();
> else
> punt();
> }
>
> I would guess that the int equality can be calculated much more rapidly
> than the String equality. String equality might be so slow in
> comparison that developers should be wary of this practice in code where
> speed matters.
>
> I am aware that sometimes there are big advantages to using Strings as
> branch-deciding parameters. I often favor this practice, but mostly in
> code that runs infrequently.
>
> But I wonder if anybody knows better. I'm just guessing. Has anybody
> seen evidence that String equality can become a time hog?
>
> Rich Hammer
>
> _______________________________________________
> Juglist mailing list
> [EMAIL PROTECTED]
> http://trijug.org/mailman/listinfo/juglist_trijug.org
>
>
_______________________________________________
Juglist mailing list
[EMAIL PROTECTED]
http://trijug.org/mailman/listinfo/juglist_trijug.org