Why does caching of string objects perform faster? I'm trying to implement String-Pool. I'm maintaining a HashMap&lt;String,String&gt; to store the keys.

public class TestStringCaching {
    static Map &lt; String, String &gt; cache = new HashMap &lt; String, String &gt; ();
    public static void main(String[] args) {
        int iter = 8000000;
        String[] temp = new String[iter];
        long st1 = System.currentTimeMillis();
        for (int i = 0; i &lt; iter; i++) {
            temp[i] = generateString();
        }
        System.out.println(System.currentTimeMillis() - st1);
        st1 = System.currentTimeMillis();
        for (int i = 0; i &lt; iter; i++) {
            temp[i] = generateString1();
        }
        System.out.println(System.currentTimeMillis() - st1);
        System.gc();
    }

    private static String generateString() {
        return new String("abc");
    }

    private static String generateString1() {
        String str = new String("abc");
        if (cache.containsKey(str))
            return cache.get(str);
        else {
            cache.put(str, str);
            return cache.get(str);
        }

    }

}


In both of the cases getString() and getString1() same number of string objects are created. But fetching from the map/cache is blistering fast compared to normal creation of String.

Why is that happening ?
Why skimp on braces?  Putting braces around the if-block in generateString() costs you almost nothing — not even an extra line of code.  Make it a habit to always include explicit braces so that you never write a disaster like this.  (Don't think that it can't happen to you!  Accidents often have more than one contributing factor — so don't be a contributing factor.)


private static String generateString1() {
    String str = new String("abc");
    if (cache.containsKey(str))
        return cache.get(str);
    else {
        cache.put(str, str);
        return cache.get(str);
    }
}



That could be better expressed as:

private static String generateString1() {
    String str = new String("abc");
    if (!cache.containsKey(str)) {
        cache.put(str, str);
    }
    return cache.get(str);
}


If you really don't like braces, putting the action on the same line as the if could also be acceptable:

private static String generateString1() {
    String str = new String("abc");
    if (!cache.containsKey(str)) cache.put(str, str);
    return cache.get(str);
}