Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing Strings

 
Anoop Krishnan
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which the fastest way to compare two strings
S1="JAVA RANCH" & S2="JAVA RANCH"
S1.equals(S2) or S1.intern()==S2.intern()
or is there any other methods which give better performance
 
Bosun Bello
Ranch Hand
Posts: 1510
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My understanding is that, since S1.intern()==S2.intern() is actually comparing references, it's faster.

Bosun
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, the == part of the operation is certainly faster if the intern() parts have already been done. But I'm sure an equals() will be faster than two intern() calls plus an ==, and it's probably faster than a single intern() plus == as well. So this approach really makes sense only if you expect to do comparisons more than once for each value, so you only pay the overhead of interning once, and reap its subsequent benefits on each compare. But I'm too lazy to do actual tests of this theory right now, so you should probably test both methods under various conditions to see which is really faster.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic