7

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:

  • deleting one letter of the word,
  • transposing two neighboring letters,
  • alteration of one letter of the word, and
  • inserting one letter to the word.

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.

2
  • @AndyTurner It seems to be a good answer :) Commented May 5, 2016 at 14:11
  • It is also worth mentioning that the Java compiler is smart enough to replace string operations (like the + operator) with StringBuilder, often making these kind of decisions unnecessary. see also stackoverflow.com/questions/1532461/… Commented May 5, 2016 at 14:27

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.