title: Look for a GC friendly way to replace substring frequently
body: <p>My goal is simply replace the substring, but very frequently. The program runs in Android.</p>
  
  <p>Such as I have a string = <code>{a} is a good {b}.</code> with a map=<code>{{a}=Bob, {b}=boy}</code>, and the result should be <code>Bob is a good boy.</code> I need to deal with such replacement for different string up to 400 times peer second because the value of map will update real time.</p>
  
  <p>However I use trie tree and Aho-Corasick automaton for high perfromance, here's the core fragment:</p>
  
  <pre><code>    val builder: StringBuilder
  
      private fun replace(str: String): String {
          if (!getFail) {
              getFail()
          }
          var p = 1
          builder.setLength(0)
          for (c in str) {
              builder.append(c)
              if (c.toInt() !in 0..126) {
                  continue // ignore non-ascii char
              }
              var k = trie[p][c.toInt()]
              while (k &gt; 1) {
                  // find a tag
                  if (end[k] != 0) {
                      val last = builder.length - end[k]
                      // replace the tag
                      values[builder.sub(last, end[k])]?.let {
                          builder.replace1(last, end[k], it)
                      }
                      p = 0
                      break
                  }
                  k = fail[k] // not find
              }
              p = trie[p][c.toInt()]
          }
          return builder.toString()
      }
  </code></pre>
  
  <p>As you can see I have used <code>StringBuilder</code> to reused memory, but finally I have to call <code>StringBuilder.toString()</code> to return the result and this operation create a new string object. Meanwhile the result's lifecycle is very short and the replacement function is called very frequently. As a result JVM will GC frequently.</p>
  
  <p>Any way to reuse the memory occupied by the short life result string? Or just some other solution.</p>