# Encasing a string in double quotes

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.

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.

DOUBLE_QUOTE_CHAR + escapeJava(query) + DOUBLE_QUOTE_CHAR;

• @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. Jun 5 '20 at 22:39
• 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. Jun 6 '20 at 14:36