Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Lua optimize concatenating with an empty string?

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.

like image 317
Niccolo M. Avatar asked Apr 01 '14 08:04

Niccolo M.


People also ask

Can you concatenate an empty string?

Concatenating with an Empty String VariableYou can use the concat() method with an empty string variable to concatenate primitive string values. By declaring a variable called totn_string as an empty string or '', you can invoke the String concat() method to concatenate primitive string values together.

Why concatenation with empty set is empty?

This is because the empty set does not add any new elements to the result. However, performing a concatenation with the empty set results in an empty set. This is because one half of the result needs to come from an element of the empty set of which there are none.

How do I concatenate strings in Lua?

The most straightforward way to concatenate (or combine) strings in Lua is to use the dedicated string concatenation operator, which is two periods ( .. ). message = "Hello, " .. "world!" -- message equals "Hello, World!" Numbers are coerced to strings. For fine-grained control over number formatting, use string.

Does string concat add space?

Add a space after the Text argument. For example: =CONCATENATE("Hello ", "World!"). The string "Hello " has an extra space added.


1 Answers

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.

like image 122
Yu Hao Avatar answered Nov 07 '22 08:11

Yu Hao