The first alternative uses regular expressions. It does look more elegant, but I didn't look at the Java source code to see what it is actually doing. Further, I don't use regular expressions much and thought I would take the opportunity to see if it would help me in my quest for performance. Regular expressions can do some complex processing, so it makes sense they may not be real fast, but for some reason I thought this option may be better.
The second alternative merely trims the string and evaluates whether the length of the trimmed string is zero (in which case, of course, the original string was all spaces). This alternative creates a new String object each time it is called and thus I thought it may have some performance problems.
Here is the code:
public static void main(String[] args) { performanceTest(" ", 1000000, 1); performanceTest(" ", 1000000, 2); performanceTest(" bogus ", 1000000, 1); performanceTest(" bogus ", 1000000, 2); } static boolean isWhiteSpaces( String s ) { return s != null && s.matches("\\s*"); } static boolean isWhiteSpaces2( String s ) { return s.trim().length() == 0; } public static void performanceTest(String s, int loops, int version) { long start = System.currentTimeMillis(); for (int i = 0; i < loops; i++) { if (version == 1) { isWhiteSpaces(s); } else { isWhiteSpaces2(s); } } System.out.println("Total time for " + loops + " loops using algorithm #" + version + ": " + (System.currentTimeMillis() - start)); }
I was surprised at the difference in the performance:
Total time for 1000000 loops using algorithm #1: 1042 Total time for 1000000 loops using algorithm #2: 41 Total time for 1000000 loops using algorithm #1: 991 Total time for 1000000 loops using algorithm #2: 41The second option, which trims the string, then compares the length, wins hands down. Now I know which option I will use in my code.