Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Which one is faster (before writing metric code)  RSS feed

 
dema rogatkin
Ranch Hand
Posts: 294
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

or

?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"instanceof" compiles to a single bytecode, while the chained method calls and string comparison of your second version compiles to many bytecodes. Although the only way to get a real answer would be to benchmark it yourself in your real application, in general, you should use language features to solve your problems -- so he first one is preferable.
 
Paul Clapham
Sheriff
Posts: 22502
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also bear in mind that the two statements do not do the same thing, so asking which is faster is not very useful.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the rare cases where you really do want an exact class match rather than an instanceof check, I would recommend forgetting about getName() and equals(), instead simply using

Still, I would usually prefer using instanceof.

In terms of performance, the difference is probably negligible anyway 99% of the time, and you could test it yourself in whatever context you need to call this, much more effectively than we can speculate for you.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jim Yingst:
In the rare cases where you really do want an exact class match rather than an instanceof check, I would recommend forgetting about getName() and equals(), instead simply using

Still, I would usually prefer using instanceof.


Notice that this is still not doing the same, as the String comparision doesn't take different ClassLoaders into account.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!