Don’t Abuse toLowerCase

Most usage of string.toLowerCase and string.toUpperCase in our programs has nothing to do with lower or upper casing  strings, all what we want to achieve most of the time is case insensitive comparison.

The problem is that toLowerCase will allocate a new string which includes array copy and produce unnecessary garbage for no good reason. The good news is, there is a better and more concise way for achieving this using String.equalsIgnoreCase(String).

  s1.equalsIgnoreCase(s2);

Here is a JMH benchmark that shows the difference between using both methods for testing string’s equality.

And the results when I run it on my machine.

Benchmark                              Mode  Cnt    Score    Error  Units
StringEqualsBenchmark.withIgnoreCases  avgt   10   18.299 ±  0.319  ns/op
StringEqualsBenchmark.withLowerCase    avgt   10  280.870 ± 14.076  us/op
Advertisements

Leave a Reply

Name and email address are required. Your email address will not be published.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

You may use these HTML tags and attributes:

<a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <pre> <q cite=""> <s> <strike> <strong> 

%d bloggers like this: