BEST PRACTICES | Techila
1093
single,single-post,postid-1093,single-format-standard,ajax_updown_fade,page_not_loaded,,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,qode-content-sidebar-responsive,qode-theme-ver-9.4.2,bridge,wpb-js-composer js-comp-ver-4.12,vc_responsive
 

BEST PRACTICES

maxresdefault

BEST PRACTICES

In your day-to-day programming activities, you must be coming across multiple situation where you need to check if a string is empty. There are various ways to do this and some use string1.equals(“”). NEVER do this.

Best way to check if string is empty or not is to use length() method. This method simply return the count of characters inside char array which constitutes the string. If the count or length is 0; you can safely conclude that string is empty.

public boolean isEmpty(String str)
{
    return str.equals("");        //NEVER do this
}

public boolean isEmpty(String str)
{
    return str.length()==0;        //Correct way to check empty
}

If you want to know the reason then continue reading further.

Lets see the source code of both methods inside String.java class.

Method length()

1
2
3
public int length() {
    return count;
}

Method equals()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
            while (n-- != 0) {
                if (v1[i++] != v2[j++])
                    return false;
            }
            return true;
        }
    }
    return false;
}

Analysis

As you can see that length() method is simply a getter method which return the count of characters in array. So it practically does not waste much CPU cycles to compute the length of string. And any String with length 0 is always going to be empty string.

Whereas equals() method takes a lot of statements before concluding that string is empty. It does reference check, typecasting if necessary, create temporary arrays and then use while loop also. So, its lot of waste of CPU cycles to verify a simple condition.

Author: techila

No Comments

Post A Comment