How is StringBuffer implementing append function without creating two objects?

后端 未结 10 1222
执念已碎
执念已碎 2021-01-30 09:22

It was an interview question. I was asked to implement the StringBuffer append function. I saw the code after the interview. But I cannot understand how the operati

10条回答
  •  借酒劲吻你
    2021-01-30 09:49

    tl;dr: In simple words, each string concatenation expression using the + character leads to a new String object with the contents of the initial strings being copied to the new one. StringBuffer holds an internal structure that expands only when needed, that characters are appended to it.

    Hey, but lots of people use the + string concatenation!

    Well, we/they shouldn't.

    In terms of memory usage, you are using an array in StringBuffer in order to hold the characters - that resizes, truth, but rarely if the algorithm applied in resizing is efficient, and only one String object that is created once toString() is called, much better than the creation of a new String object on each + concatenation.

    In terms of time complexity, characters are copied only once from _chars to the new string (O(n) time complexity), which in general is must better than string concatenation using the + operator, on which each operation leads to a new copy of the characters to a new object, leading to O(1 + 2 + .... + n) = O(n^2) operations.

    Should I implement one on my own?

    It would be good for you in terms of excercise, but modern languages provide native StringBuffer implementations to use it in production code.

    In four simple steps:

    1. Create a MyCustomStringBuilder class that internally (privately) holds an array (let's name it _chars) of characters of a fixed initial size. This array will hold the string characters.
    2. Add an expanding method that will increase the size of _chars once the holding string character length exceeds its length. (What you are practically doing, is implementing a simple version of an ArrayList internally).
    3. When using the stringBufferInstance.append(String s) method, add characters to _chars, increasing its size if needed.
    4. In your toString() method implementation, you can simply create a string using the array:

      public String toString() {
          return new String(_chars);
      }
      

提交回复
热议问题