We use (string != null || string.trim().length() == 0) to check if string is empty. This way is said to be inefficient since string.trim() creates a new string object just to check if string contains any non-whitespace character.
It is recommended to consider creating a static function that loops through a string, checking Character.isWhitespace() on each character and returning false if a non-whitespace character is found.
Can you please let me know what would be more expensive 1. Creating new string object 2. Calling a method which actually iterate through string and checks for non-whitespace character
I'll weigh in with the Standard Optimization Answer: "It probably doesn't matter". Compared to all the work going on in a non-trivial program and considering that modern VM's handle short-term object creation better than they used to, creating a single extra String object probably will not have an impact. That said, if your program pumps millions of Strings through this code, there is bound to be some impact. Have a look at the Java Platform Performance book. It details how to benchmark code and compare different implementations to determine which is best.
Also, go look at the implementation of String.trim() -- it returns the original String, unaltered, most of the time. Only if trim() actually needs to return a different String does it actually create a new one -- i.e., only if there was actually trailing or leading whitespace. I'd say the easy expression above is going to be good enough in virtually any circumstance.
I totally agree that this is likely premature optimization.
But for the case that it is not, the most efficient way also depends on the typical usage patterns of the code. For example, if you know that 99% of the Strings you test will consist of exactly one white space, the "short circuit" optimization proposed by Bill - while making sense in the general case - would probably *decrease* performance.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus