In my Android project, I have a singleton class called Question which will be used 90% of the time while the application is running. The class contains two static String variables named question and answer, as the new instance is called repeatedly with different strings for question and answer, so a new String object is created every time. I was thinking about changing the String variables to StringBuilder and replace the contents every time.
Here is the code with String variables:
public class Question {
private static Question mQuestionClass = null;
private static String mQuestion = "";
private static String mAnswer = "";
private Question() {
}
public static Question getQuestionInstance(String question, String answer) {
if (mQuestionClass == null) {
mQuestionClass = new Question();
}
mQuestion = question;
mAnswer = answer;
return mQuestionClass;
}
}
Here is the code with StringBuilder variables:
public class Questiontwo {
private static Questiontwo mQ2 = null;
private static StringBuilder mQ = null;
private static StringBuilder mA = null;
private Questiontwo() {
}
public static Questiontwo newInstance(String q, String a) {
if (mQ2 == null) {
mQ2 = new Questiontwo();
}
if (mQ == null) {
mQ = new StringBuilder(q);
}
mQ = mQ.replace(0, mQ.length(), q);
if (mA == null) {
mA = new StringBuilder(a);
}
mA = mA.replace(0, mA.length(), a);
return mQ2;
}
}
Which one should I prefer to use as less memory as possible?
StringBuilderwhen you dont use append here ? I dont see neither+=on string in heavy loadedfor loop? Your code does not needStringBuilder