Search code examples
javastringbuilderropes

StringBuilder vs Ropes


Good morning,

I am writing a language parser, and am looking for the best structure to use for a rollback cache which currently does the following:

  • When requesting a new character from the stream, the character is added to the cache, in case a rollback is requested.
  • When a rollback is requested, go back to a certain point in the cache so that when another character is requested, it gets it from there instead.
  • When a token is found, remove everything in the rollback cache up to the current position.

So in short, I would love to know which you feel to be the best data structure for:

  • Priority 1: appending characters (codePoints would be a welcome addition)
  • Priority 2: Doing a substring (such as StringBuilder.delete(...)) on the data structure (or clearing completely)
  • Priority 3: Being able to create a string of the cache (e.g. StringBuilder.toString())

I hope to hear from you soon!


Solution

  • If I were you, for such a specialised use and with possible performance and resource constraints, I'd implement my own buffer from primitives. I think it's more trouble adapting existing structures. Of course, if it didn't hurt, I'd try to conform to the well known relevant interfaces, such as CharSequence, Appendable, List, etc.