Reputation: 3719
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.
Upvotes: 7
Views: 7573
Reputation: 140309
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.
Upvotes: 11