I'm trying to implement String-Pool. I'm maintaining a HashMap<String,String>
to store the keys.
public class TestStringCaching {
static Map < String, String > cache = new HashMap < String, String > ();
public static void main(String[] args) {
int iter = 8000000;
String[] temp = new String[iter];
long st1 = System.currentTimeMillis();
for (int i = 0; i < iter; i++) {
temp[i] = generateString();
}
System.out.println(System.currentTimeMillis() - st1);
st1 = System.currentTimeMillis();
for (int i = 0; i < 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 ?
generateString2(){ return "abc";}
? \$\endgroup\$ArrayCopy
which is used instead ofjava.util.Arrays
because the JDOM code needs to run on Java5 which does not have thecopyOf
methods in java.util.Arrays. \$\endgroup\$gc()
is necessary there. \$\endgroup\$