kdn251 / interviews

Everything you need to know to get the job.
https://www.youtube.com/channel/UCKvwPt6BifPP54yzH99ff1g?view_as=subscriber
MIT License
62.76k stars 12.83k forks source link

Improving String concatenation #188

Open Itayventura opened 3 years ago

Itayventura commented 3 years ago

String are an immutable object in Java. Therefore, concatenating Strings via the '+' operator creates a lot of Intermediate garbage Strings. Specifically, if the Input contains N words in the sentence, then the original solution will generate 2*N intermediate Strings. For instance, for input "Hello World from github" The intermediate Strings are: "", "github", "github ", "github from", "github from ", github from World", "github from World ", and the result itself: "github from World Hello".

A better approach would be using the StringBuilder object which does not create intermediate Strings.