1
\$\begingroup\$

I need to add some characters to a String before using it for an API call. The idea is to add a " char both at the beginning and at the end of the String, to make sure the API does an exact search for the input string.

Version 1:

StringBuilder(escapeJava(query))
                .insert(0, DOUBLE_QUOTE_CHAR)
                .append(DOUBLE_QUOTE_CHAR)
                .toString();

Version 2:

String.format("%c" + escapeJava(query) + "%c", DOUBLE_QUOTE_CHAR, DOUBLE_QUOTE_CHAR)

I prefer the readability of the first one, but I don't think it will be as quick as the second version, and might look like overkill.

\$\endgroup\$
4
\$\begingroup\$

Version 1 uses insert(0, ...) which has to move over all the characters already in the StringBuilder's buffer, so is unnecessarily wasting time.

A more efficient construct would be:

StringBuilder().append(DOUBLE_QUOTE_CHAR)
               .append(escapeJava(query))
               .append(DOUBLE_QUOTE_CHAR)
               .toString();

Version 2 uses StringBuilder under the hood, to construct "%c" + escapeJava(query) + "%c", so your belief the second version is faster may be in error.

Which leads us to the most efficient, most readable version:

DOUBLE_QUOTE_CHAR + escapeJava(query) + DOUBLE_QUOTE_CHAR;
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Does it really make a difference to performance? \$\endgroup\$
    – Peilonrayz
    Jun 5 '20 at 22:32
  • 1
    \$\begingroup\$ @Peilonrayz Somehow, I doubt this is the performance bottleneck of the application. But avoiding the memcopy caused by insert will be a win, as will avoiding the format. I'll run some performance numbers later, but as always, with hotspot JIT optimizations, getting accurate profiling requires careful work. \$\endgroup\$
    – AJNeufeld
    Jun 5 '20 at 22:39
  • \$\begingroup\$ True, true. Coming from Python I've gained an, unhealthy, level of scepticism between theory and practice. Sometimes there's magic optimizations that are really quite odd. If it's lots of work, don't bother :) \$\endgroup\$
    – Peilonrayz
    Jun 5 '20 at 22:42
  • 1
    \$\begingroup\$ If you want to improve performance then use the length of the escaped query + 2 as initial capacity of the StringBuilder; that will avoid multiple allocations happening out of view. Note that using the plus operator twice may use two string builders - although in the end that's implementation specific of course. All this doesn't matter if it is not in the critical part though, so yeah, the last one is definitely the most easy to read. \$\endgroup\$ Jun 6 '20 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.