Cheap string building/formatting for inputstreams and timer displays?
I am having a fair amount of memory problems with my app. I think I have my bitmaps sorted out, my current problem seems to stem from String开发者_如何学运维s. I have 2 functions that happen often and need to make sure they are solid.
First is converting an inputstream to a string.
The second one is to format a timer display as in a mediaplayer. This happens every second.
Are there any obvious inefficiencies in these functions?? Thanks
**edit, did a quick edit of the maketimestring, for an obvious inneficiency I spotted where I was pulling a string from resources every time.
private static StringBuilder sBuilder = new StringBuilder();
private static Formatter sFormatter = new Formatter(sBuilder, Locale.getDefault());
private static final Object[] sTimeArgs = new Object[5];
public static String makeTimeString(String durationFormat, long secs) {
sBuilder.setLength(0);
final Object[] timeArgs = sTimeArgs;
timeArgs[0] = secs / 3600;
timeArgs[1] = secs / 60;
timeArgs[2] = (secs / 60) % 60;
timeArgs[3] = secs;
timeArgs[4] = secs % 60;
return sFormatter.format(durationformat, timeArgs).toString();
}
public static String formatContent(InputStream is) throws IOException {
if (is == null)
return "";
sBuilder.setLength(0);
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = buffer.readLine()) != null) {
sBuilder.append(line).append("\n");
}
buffer.close();
buffer = null;
return sBuilder.toString().trim();
}
Keeping the StringBuilder as a class variable means that its internal buffer stays allocated for the life of the class. Unless you need the character data as both a StringBuilder and a String, you should create a new StringBuilder as a local variable inside formatContent() each time it is called. Alternatively, if you can make do with a CharSequence instead of a String, and just use the StringBuilder instead of constructing a String. (That doesn't work, of course, if you have to eventually pass it to an API outside your control that requires a String.)
精彩评论