i wrote this piece of code to compare String and StringBuffer.
public static void main(String[] args) {
String inputText = "let us learn pig latin";
usingString(inputText);
usingStringBuffer(inputText);
}
public static void usingString(String input) {
String pigLatinText = new String();
input = input.trim();
String tokens[] = input.split(" ");
for (int i = 0; i < tokens.length; i++) {
String temp = tokens[i];
temp = temp.substring(1) + temp.charAt(0);
temp += "ay";
pigLatinText += temp+" ";
}
System.out.println("Using String :"+pigLatinText);
}
public static void usingStringBuffer(String input) {
String pigLatin = new String();
input = input.trim();
String tokens[] = input.split(" ");
for (int i = 0; i < tokens.length; i++) {
StringBuffer temp = new StringBuffer(tokens[i]);
temp.append(temp.charAt(0)).deleteCharAt(0);
temp.append("ay");
pigLatin += temp+" ";
}
System.out.println("Using String Buffer :"+pigLatin);
}
I know String + operator internally uses StringBuilder's append(). And it creates temporary objects as it is immutable.
I am trying to prove that by counting the number of objects that are created while using String and by using StringBuffer.
Using Static variable to count the number of objects is not going to help me as i cannot modify the String class. i found this link. It seems promising. but i don't know how to modify the Object.java file.
using System.currentTimeInMillis() before and after doesn't help as this operation is very small. So my questions are
- is there any way to analyze or compare the performance of these classes ?
- How to count the number of String objects created in a program?
Profilefeature that will allow you to see how manyStringare created.