18 July 2010

"".equals(val.trim()) vs. 0 == val.trim().length()

Trimming string values a quite often task on the Web. I personally prefer avoid this in origin: just do not store redundant symbols. But you know, shit is happened... Sometimes data you have to use, came from side you can not control. Or even trimming is assumed by protocol.

String transformations are heavy by nature, but it is not a problem if operation is not time sensitive.

Not sure where and when I picked this habit, but usually I used construction:

if (null == value || "".equals(value.trim())) {
    // data is empty or blank
}

But recently I had been informed that this check is much slower compare to:

if (null == value || 0 == value.trim().length()) {
    // data is empty or blank
}

From my look point they both are heavy and should not be used in code that pretends to be a quick. It is even funny to hear about performance tricks in cases where it never appear to be meaningful. But I become interested how much it slower in fact. So, decided to make a quick test.