Which codes are more efficient?

1a) for(int i=0;i<100;i++){
if(a[i] == 0 && a[i]==1)//a is int
System.out.println(“abc”);
}
b) for(int i=0;i<100;i++){
if(a[i] != 0 || a[i]!=1)continue;
System.out.println(“abc”);
}

2a) for(int i=0;i<100;i++){
System.out.println (this.getObject1().getObject2().getText());
}
b)
Object2 o2 = this.getObject1().getObject2();
for(int i=0;i<100;i++){
System.out.println(o2.getText());
}

3a) for(int i=0;i<100;i++){
if(str.equal(“1”))
System.out.println(“str”);
}
b) for(int i=0;i<100;i++){
if(Integer.parseInt(str) == 1)
System.out.println(“str”);
}
c) for(int i=0;i<100;i++){
if(str.charAt(0) == ‘1’)
System.out.println(“str”);
}

a) use a profiler
b) all of those versions are about equally slow/fast… the most time is spend in the print method

to be honest … if you’re lonely try to find someone in a chatroom…

There is an answer for each, but it looks to much like some kind of homework for me to give em.

[quote]to be honest … if you’re lonely try to find someone in a chatroom…
[/quote]
Or, er, get out more and try to meet some girls :wink:

Cas :slight_smile:

[quote]1a)
if(a[i] == 0 && a[i]==1)
[/quote]
Interesting…

ANywy, the answer is “they’re all the same” except one.

That CAN return true with some tricky threading and some luck. ;D

1 will be fastest, if a is null :slight_smile:

[quote]That CAN return true with some tricky threading and some luck. ;D
[/quote]
Dang. Fair enough :slight_smile:

When replying, I momentarily wonderd if the compiler would compile it out, and then remembered:


void blah() throws Exception
{
throw new Exception();
String a = "poor little me";
}

…does not compile, but:


void blah() throws Exception
{
if( true )
  throw new Exception();
String a = "poor little me";
}

does. And so does:


void blah() throws Exception
{
if( 1 == 1 )
   throw new Exception();
String a = "poor little me";
}

…so, hotspot might compile it out, but it’s far from assured ;).

Depends what he means by efficient and what the job is that you want it to do as if it doesn’t do the right job, it isn’t that efficient.