I have the following code inside a loop statement.
In the loop, strings are appended to sb(StringBuilder) and checked whether the size of sb has reached 5MB.
If you loop 1000 times, you will generate 1000String, then convert into "UTF-8 Byte" array, to get the length.
I would reduce the conversion by storing the first length. Then, on each loop, get the length of the added value only, then this is just an addition.
int length = sb.toString().getBytes("UTF-8").length;
for(String s : list){
sb.append(s);
length += s.getBytes("UTF-8").length;
if(...){
...
}
}
This would reduce the memory used and the conversion cost