6

I try to get a better understanding of Strings. I am basically making a program that requires a lot of strings. However, a lot of the strings are very, very similar and merely require a different word at the end of the string.

E.g.

String one = "I went to the store and bought milk"
String two = "I went to the store and bought eggs"
String three = "I went to the store and bought cheese"

So my question is, what approach would be best suited to take when dealing with strings? Would concatenating 2 strings together have any benefits over just having static strings in, say for example, performance or memory management?

E.g.

String one = "I went to the store and bought "
String two = "milk" 
String three = "cheese"
String four = one + two
String five = one + three

I am just trying to figure out the most optimal way of dealing with all these strings. (If it helps to put a number of strings I am using, I currently have 50 but the number could surplus a huge amount)

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Awesomasaurus
  • 75
  • 2
  • 6
  • 14
    Readability is more important. I don't think there is a real performance difference between the two – Spooky Jan 07 '16 at 16:34
  • `static final` Strings, [well explained here](http://stackoverflow.com/questions/1415955/private-final-static-attribute-vs-private-final-attribute) Strings would be a good idea for the constant parts. – pietv8x Jan 07 '16 at 16:36
  • 2
    Localization is sometimes easier with literal strings than generated strings. – Andy Thomas Jan 07 '16 at 16:37
  • 2
    Could you define "huge" and "a lot"? Because the only number you gave (50) is very very very far from being "a lot" for a computer. 50 String of 40 characters make 4KB of memory. What are you trying to achieve? What are all these hard-coded strings for? That looks like an X/Y problem to me. – JB Nizet Jan 07 '16 at 16:38
  • Pardon me for saying exaggerating the number of strings, it might have been misleading. The hard-coded strings in the above example were just examples. The strings are actually various website URLs and the change in strings would navigate to different pages. That's why they only require minor adjustments. – Awesomasaurus Jan 07 '16 at 16:46
  • 2
    Code should be **readable but also maintainable**. If the strings are used in multiple places or likely to change putting them in variables would likely be a more suitable option. Either way the question is primarily opinion based and is really up to the developer to make a judgement call on which option to take. – ug_ Jan 07 '16 at 16:48
  • As soon as you concatenate, you have a new `String` that contains all of the characters. Unless you are going to allow your concatenated `String`s to be garbage collected, I don't see any performance benefit. One more vote for readability and maintainability. – Erick G. Hagstrom Jan 07 '16 at 16:49
  • you don't need Strings two and three, you can just do `String s = one + "milk";` if you only use this word once... And you can define the `String milk = "milk";` that simple (: –  Jan 07 '16 at 16:54

7 Answers7

2

As spooky has said the main concern with the code is readability. Unless you are working on a program for a phone you do not need to manage your resources. That being said, it really doesn't matter whether you create a lot of Strings that stand alone or concatenate a base String with the small piece that varies. You won't really notice better performance either way.

Erick G. Hagstrom
  • 4,873
  • 1
  • 24
  • 38
Matt Quick
  • 70
  • 9
0

You may set the opening sentence in a string like this

String openingSentence = "I went to the store and bought";

and alternate defining each word alone, by defining one array of strings like the following ::

String[] thingsToBeBought = { "milk", "water", "cheese" .... };

then you can do foreach loop and concatenate each element in the array with the opening sentence.

Akram Qalalwa
  • 103
  • 11
0

Performance wise final static strings are always better as they are generated during compile time. Something like this

final static String s = "static string";

Non static strings and strings concatenated as shown in the other example are generated at runtime. So even though performance will hardly matter for such a small thing, The second example is not as good as the first one performance wise as in your code :

// not as good performance wise since they are generated at runtime
String four = one + two
String five = one + three
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
0

In Java, if you concatenate two Strings (e.g. using '+') a new String is created, so the old memory needs to be garbage collected. If you want to concatenate strings, the correct way to do this is to use a StringBuilder or StringBuffer.

Given your comment about these strings really being URLs, you probably want to have a StringBuilder/StringBuffer that is the URL base, and then append the suffixes as needed.

Julie
  • 1,941
  • 3
  • 17
  • 30
  • Thanks for your reply. However, I don't necessarily want to take a concatenating approach. I was merely asking for a good approach when it came to strings like these. Whether concatenating is more optimal than static strings. – Awesomasaurus Jan 07 '16 at 17:05
  • @Awesomasaurus to answer that question, concatenation is actually less optimal from a performance perspective. As mentioned above, it creates multiple strings that Java then needs to garbage collect. – Julie Jan 07 '16 at 21:24
0

Since you are going to use this string as URL, I would recommend to use StringJoiner (in case your are using JAVA 8). It will be as efficient as StringBuilder (will not create a new string every time you perform concatenation) and will automatically add "/" between strings.

StringJoiner myJoiner = new StringJoiner("/")
dmitryvinn
  • 392
  • 3
  • 9
0

There will be no discernable difference in performance, so the manner in which you go about this is more a matter of preference. I would likely declare the first part of the sentence as a String and store the individual purchase items in an array.

Example:

String action = "I went to the store and bought ";
String [] items = {"milk", "eggs", "cheese"};

for (int x = 0; x< items.length; x++){
     System.out.println(action + items[x]);
}
Coop
  • 309
  • 1
  • 9
0

Whether you declare every possible String or separate Strings to be concatenated isn't going to have any measurable impact on memory or performance in the example you give. In the extreme case of declaring truly large numbers of String literals, Java's native hash table of interned Strings will use more memory if you declare every possible String, because the table's cached values will be longer.

If you are concatenating more than 2 Strings using the + operator, you will be creating extra String objects to be GC'd. For example if you have Strings a = "1" and b = "2", and do String s = "s" + a + b;, Java will first create the String "s1" and then concatenate it to form a second String "s12". Avoid the intermediate String by using something like StringBuilder. (This wouldn't apply to compile-time declarations, but it would to runtime concatenations.)

If you happen to be formatting a String rather than simply concatenating, use a MessageFormat or String.format(). It's prettier and avoids the intermediate Strings created when using the + operator. So something like, String urlBase = "http://host/res?a=%s&b=%s"; String url = String.format(urlBase, a, b); where a and b are the query parameter String values.

Kevin Condon
  • 1,618
  • 10
  • 16