Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ternary operator with strings

 
Mary McCartney
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider these 2 methods, both of which convert null strings to empty strings:

private static final String N2E1(String str){
if (str == null){
str = "";
}
return str;
}

private static final String N2E2(String str){
return str == null ? "" : str;
}

Assuming it will be called a lot, is there a performance difference, or will the compiler just optimize N2E1 to do what N2E2 does anyway?

Thanks for your help!
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They would likely compile to identical bytecode.
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Almost.



compiles to

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ken Blair:
Almost.


Here the ternary operator compiles to slightly worse code!

But it's likely that HotSpot would optimize the double branch to the methodB version with the multiple returns.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd also assume that a goto is a very cheap operation on most platforms.
 
Nishant Verma
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest Friedman-Hill, Ken Blair, Ilja Preuss

You guys rock really
 
S Thanigaivel
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ken, can you explain in detail the below calculations and also how you derived it?


compiles to

[/QB]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The disassembly comes from the "javap" tool that comes in the JDK. "javap -c MyClassName" will show a display like the one given here.
 
S Thanigaivel
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
The disassembly comes from the "javap" tool that comes in the JDK. "javap -c MyClassName" will show a display like the one given here.



Thats interesting! Thank you Ernest
 
Mary McCartney
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was not aware of that javap tool. Thanks everyone for the info!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic