Java - Fastest way to check the size of String

前端 未结 3 2051
无人共我
无人共我 2021-02-08 22:55

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.



        
3条回答
  •  花落未央
    2021-02-08 23:36

    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

提交回复
热议问题