When I have a String that I need to concatenate a single char to its end,
should I prefer s = .... + \']\'
over s = .... + \"]\"
for any performance re
When I have a String that I need to concatenate a single char to its end, should I prefer s = .... + ']' over s = .... + "]" for any performance reason?
There are actually two questions here:
Q1: Is there a performance difference?
Answer: It depends ...
In some cases, possibly yes, depending on the JVM and/or the bytecode compiler. If the bytecode compiler generates a call to StringBuilder.append(char)
rather than StringBuilder.append(String)
then you would expect the former to be faster. But the JIT compiler could treat these methods as "intrinics" and optimize calls to append(String)
with a one character (literal) string.
In short, you would need to benchmark this on your platform to be sure.
In other cases, there is definitely no difference. For example, these two calls will be compiled identical bytecode sequences because the concatenation is a Constant Expression.
System.out.println("234" + "]");
System.out.println("234" + ']');
This is guaranteed by the JLS.
Q2: Should you prefer one version over the other.
Answer:
In the general sense, this is likely to be a premature optimization. You should only prefer one form over the other for performance reasons if you have profiled your code at the application level and determined that the code snippet has a measurable impact on performance.
If you have profiled the code, then use the answer to Q1 as a guide.
And if it was worth trying to optimize the snippet, then is essential that you rerun your benchmarking / profiling after optimizing, to see if it made any difference. Your intuition about what is fastest... and what you have read in some old article on the internet ... could be very wrong.