gpt4 book ai didi

lua - 全局变量很糟糕,这是否会以任何方式提高性能?

转载 作者:行者123 更新时间:2023-12-04 05:11:25 26 4
gpt4 key购买 nike

我在 LuaJIT 中工作,并将我所有的库和诸如此类的东西都存储在“foo”中,如下所示:

foo = {}; -- The only global variable
foo.print = {};
foo.print.say = function(msg) print(msg) end;
foo.print.say("test")

现在我想知道,使用元表并保持所有图书馆都在本地有帮助吗?或者没关系。我想到的是这个:
foo = {};
local libraries = {};

setmetatable(foo, {
__index = function(t, key)
return libraries[key];
end
});

-- A function to create a new library.
function foo.NewLibrary(name)
libraries[name] = {};

return libraries[name];
end;

local printLib = foo.NewLibrary("print");

printLib.say = function(msg) print(msg) end;

-- Other file:
foo.print.say("test")

我现在真的没有工具来对此进行基准测试,但是将库的实际内容保存在本地表中会提高性能吗?哪怕是一点点?

我希望我已经明确了这一点,基本上我想知道的是:性能方面是第二种方法更好吗?

如果有人可以链接/详细解释如何在 Lua 中处理全局变量,这也可以解释这一点,那也很棒。

最佳答案

don't really have the tools to benchmark this right now



你当然知道。
local start = os.clock()
for i=1,100000 do -- adjust iterations to taste
-- the thing you want to test
end
print(os.clock() - start)

对于性能,您几乎总是希望进行基准测试。

would keeping the actual contents of the libraries in a local table increase performance at all?



与第一个版本的代码相比?理论上没有。

你的第一个例子(去掉不必要的垃圾):
foo = {}
foo.print = {}
function foo.print.say(msg)
print(msg)
end

要使用打印功能需要三个表查找:
  • 索引 _ENV 与“foo”
  • 索引foo带有“打印”字样的表
  • 索引foo.print表“说”。

  • 你的第二个例子:
    local libraries = {}
    libraries.print = {}
    function libraries.print.say(msg)
    print(msg)
    end

    foo = {}
    setmetatable(foo, {
    __index = function(t, key)
    return libraries[key];
    end
    });

    要使用打印功能,现在需要进行五次表查找以及其他额外工作:
  • 索引 _ENV 与“foo”
  • 索引foo带有“打印”字样的表
  • Lua 发现结果为 nil,检查是否 foo有一个元表,找到一个
  • 带有“__index”的索引元表
  • 检查结果是表还是函数,Lua 发现它是一个函数,所以它用键
  • 调用它
  • 索引libraries带有“打印”
  • 索引print带有“说”的表

  • 一些额外的工作是在 C 代码中完成的,所以它会比在 Lua 中实现的速度更快,但肯定会花费更多的时间。

    使用我上面展示的循环进行基准测试,第一个版本在 vanilla Lua 中大约是第二个版本的两倍。在 LuaJIT 中,两者的速度完全相同。显然,差异在 LuaJIT 中在运行时得到了优化(这非常令人印象深刻)。只是为了说明基准测试的重要性。

    旁注:Lua 允许你为 __index 提供一个表,这将导致与您的代码等效的查找:
    setmetatable(foo, { __index = function(t, key) return libraries[key] end } )

    所以你可以写:
    setmetatable(foo, { __index = libraries })

    这也恰好要快得多。

    关于lua - 全局变量很糟糕,这是否会以任何方式提高性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14881331/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com