Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String vs Char Array vs String Builder (efficiency performance)

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.

like image 644
Felipe Centeno Avatar asked May 05 '16 14:05

Felipe Centeno


People also ask

Is StringBuilder more efficient than String?

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.

How much faster is StringBuilder than 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).

Is StringBuilder less efficient or more efficient?

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.

Why is StringBuilder more efficient?

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.


1 Answers

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.

like image 67
Andy Turner Avatar answered Sep 17 '22 01:09

Andy Turner