简体   繁体   中英

Appending Strings vs appending chars in Java

I am trying to solve an algorithmic task where speed is of primary importance. In the algorithm, I am using a DFS search in a graph and in every step, I add a char and a String. I am not sure whether this is the bottleneck of my algorithm (probably not) but I am curious what is the fastest and most efficient way to do this.

At the moment, I use this:

transPred.symbol + word

I think that there is might be a better alternative than the "+" operator but most String methods only work with other Strings (would converting my char into String and using one of them make a difference?).

Thanks for answers.

EDIT:

for (Transition transPred : state.transtitionsPred) {
            walk(someParameters, transPred.symbol + word);
        }

transPred.symbol is a char and word is a string

A very common problem / concern.

Bear in mind that each String in java is immutable. Thus, if you modify the string it actually creates a new object. This results in one new object for each concatenation you're doing above. This isn't great, as it's simply creating garbage that will have to be collected at some point.

If your graph is overly large, this might be during your traversal logic - and it may slow down your algorithm.

To avoid creating a new String for each concatenation, use the StringBuilder . You can declare one outside your loop and then append each character with StringBuilder.append(char) . This does not incur a new object creation for each append() operation.

After your loop you can use StringBuilder.toString() , this will create a new object (the String) but it will only be one for your entire loop.

Since you replace one char in the string at each iteration I don't think that there is anything faster than a simple + append operation. As mentioned, Strings are immutable, so when you append a char to it, you will get a new String object, but this seems to be unavoidable in your case since you need a new string at each iteration.

If you really want to optimize this part, consider using something mutable like an array of chars. This would allow you to replace the first character without any excessive object creation.

Also, I think you're right when you say that this probably isn't your bottleneck. And remember that premature optimization is the root of all evil etc. (Don't mind the irony that the most popular example of good optimization is avoiding excessive string concatenation).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM