I am writing a spell corrector that gives suggestions to the user. To do this, I am using words one and two edit distance away. There are four techniques:
Some of these require many iterations through the word, and doing things like swapping two letters, or adding a letter in the middle of a string.
I know String are immutable in java, and that insert from string builder might create copies of the string as necessary, so I was wondering if an array of char would make this any faster.
Note that regular string concatenations are faster than using the StringBuilder but only when you're using a few of them at a time. If you are using two or three string concatenations, use a string.
Using StringBuilder resulted in a time ~6000 times faster than regular String 's. What it would take StringBuilder to concatenate in 1 second would take String 1.6 hours (if we could concatenate that much).
StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
StringBuilder is efficient in the first example because it acts as a container for the intermediate result without having to copy that result each time - when there's no intermediate result anyway, it has no advantage.
It is very hard to say - without more context - which of various approaches will be the fastest. (Or even if the difference in speed is relevant; or that speed is the most important metric).
You would need to benchmark the various approaches for your situation.
StringBuilder
is just a wrapper around a char[]
, adding functionality like resizing the array as necessary; and moving elements when you insert/delete etc.
It might be marginally faster to use the char[] directly for some things, but you'd lose (or have to reimplement) a lot of the useful functionality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With