Question

I have two strings. One of them is often (but not always) empty. The other is huge:

a = ""
b = "... huge string ..."

I need to concatenate the two strings. So I do the following:

return a .. b

But, if a is empty, this would, temporarily, unnecessarily create a copy of the huge string.

So I thought to write it as follows:

return (a == "" and b) or (a .. b)

This would solve the problem. But, I was wondering: does Lua optimize a concatenation that involves an empty string? That is, if we write a .. b, does Lua check to see if either of the strings is empty and return the other one immediately? If so, I could simply write a ..b instead of the more elaborate code.

Was it helpful?

Solution

Yes, it does.

In the Lua 5.2 source code luaV_concat:

if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) {
  if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT))
    luaG_concaterror(L, top-2, top-1);
}
else if (tsvalue(top-1)->len == 0)  /* second operand is empty? */
  (void)tostring(L, top - 2);  /* result is first operand */
else if (ttisstring(top-2) && tsvalue(top-2)->len == 0) {
  setobjs2s(L, top - 2, top - 1);  /* result is second op. */
}
else {
  /* at least two non-empty string values; get as many as possible */

The two else if parts are exactly doing the job of optimizing string concatenation when one of the operand is an empty string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top