Lua是否优化与空字符串连接?

我有两个字符串。其中一个经常(但不总是)为空。另一个则非常大:

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

我需要将这两个字符串连接起来。因此我执行以下操作:

return a .. b

但是,如果 a 是空的,那么这将临时地、不必要地创建一个巨大字符串的副本。

因此,我考虑将其编写为:

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

这将解决问题。但是,我想知道:Lua 是否会优化涉及空字符串的连接?也就是说,如果我们写a .. b,Lua 是否会检查其中的一个字符串是否为空并立即返回另一个字符串?如果是这样,我可以简单地写a ..b而不是更复杂的代码。

点赞
用户1009479
用户1009479

是的,它确实如此。

在 Lua 5.2 源代码中的 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 */

这两个 else if 部分正是在其中一个操作数为空字符串时优化字符串拼接的工作。

2014-04-01 09:07:44