我有两个字符串。其中之一经常(但不总是)是空的。另一个是巨大的:
a = ""
b = "... huge string ..."
我需要连接两个字符串。所以我执行以下操作:
return a .. b
但是,如果
a
为空,这将暂时不必要地创建一个巨大字符串的副本。所以我想写成这样:
return (a == "" and b) or (a .. b)
这将解决问题。但是,我想知道:Lua 是否优化了涉及空字符串的连接?也就是说,如果我们写
a .. b
, Lua 是否会检查其中一个字符串是否为空并立即返回另一个字符串?如果是这样,我可以简单地写 a ..b
而不是更复杂的代码。
最佳答案
是的,它确实。
在 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
当操作数之一是空字符串时,部分正是在做优化字符串连接的工作。
关于string - Lua 是否优化连接空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22781134/