I am writing this blog from a very rural village of Bihar, India. The common problem I found was people are not utilizing the time in best of work. Many of the kids go to the market to bring one-one item at a time. Alright, are we engineers also follow the same trend.
We use String as default and then we keep adding things in it. Something like:
String dontUse = "This";
dontUse +="is not right";
Alright, here is a small code I have written to understand the estimated time.
public class StringBufferExample {
public static void main(String[] args) {
String[] dontUse = new String[10000];
//StringBuffer[] dontUse = new StringBuffer[10000];
for(int i=0;i<10000;i++) { }
long startTime = System.nanoTime();
for(int i=0;i<10000;i++) {
dontUse[i]= new String("this");
// dontUse[i]= new StringBuffer("this");
}
for(int i=0;i<10000;i++) {
dontUse[i]+="is wrong";
// dontUse[i].append("is wrong");
}
long endTime = System.nanoTime();
System.out.println(endTime - startTime);
}
}
Approx Time taken from this code: 5501435(ns) whereas if you run the commented code, it will take: 2258812(ns)
So, not visible but normal String operation for "simply" addition of two string is "twice" costlier than StringBuffer.
Running: javap -c -classpath . StringBufferExample (copying those lines which are costly), will clearly tell you why String operation is a costly affair(actually it was never a String operation, it changes things to StringBuffer and then again convert it by toString to String).
64: if_icmpge 97
67: new #6; //class java/lang/StringBuilder
70: dup
74: aload_1
75: iload 4
77: dup2_x1
78: aaload
90: aastore
Now in the next blog, I will cover how StringBuffer handles the capacity, how it enlarge its capacity and when. It's a pretty simple code written in JDK.
3 comments:
I would suggest using StringBuilder for most of cases unless and until you want to share this object with multiple threads.
The problem with String is it will never get garbage collected unless you explicitly create it with new .
I would suggest using StringBuilder for most of cases unless and until you want to share this object with multiple threads.
The problem with String is it will never get garbage collected unless you explicitly create it with new .
Yes Raghu, that's a important point you mentioned. Thank you.
Post a Comment