【问题标题】:Lua garbage collection and C userdataLua 垃圾收集和 C 用户数据
【发布时间】:2011-02-09 13:08:21
【问题描述】:

在我的游戏引擎中,我使用 userdata 将我的 Vector 和 Color 对象暴露给 Lua。

现在,对于每个在 Lua 脚本中本地创建的 Vector 和 Color,Luas 内存使用量都会上升一点,直到垃圾收集器运行时才会下降。

垃圾收集器在我的游戏中造成了一个小的延迟。

Vector 和 Color 对象如果只用作参数,不应该立即删除吗?例如:myObject:SetPosition( Vector( 123,456 ) )

他们现在不是 - Lua 的内存使用量上升到每秒 1.5 MB,然后出现延迟峰值并回到大约 50KB。

  • 我该如何解决这个问题,它甚至可以解决吗?

【问题讨论】:

    标签: c++ lua


    【解决方案1】:

    您可以在退出函数后运行lua_setgcthreshold(L,0) 强制立即进行垃圾回收。

    编辑:对于 5.1,我看到以下内容:

    int lua_gc (lua_State *L, int what, int data);
    
    Controls the garbage collector.
    
    This function performs several tasks, according to the value of the parameter what:
    
        * LUA_GCSTOP: stops the garbage collector.
        * LUA_GCRESTART: restarts the garbage collector.
        * LUA_GCCOLLECT: performs a full garbage-collection cycle.
        * LUA_GCCOUNT: returns the current amount of memory (in Kbytes) in use by Lua.
        * LUA_GCCOUNTB: returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024.
        * LUA_GCSTEP: performs an incremental step of garbage collection. The step "size" is controlled by data (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of data. The function returns 1 if the step finished a garbage-collection cycle.
        * LUA_GCSETPAUSE: sets data as the new value for the pause of the collector (see §2.10). The function returns the previous value of the pause.
        * LUA_GCSETSTEPMUL: sets data as the new value for the step multiplier of the collector (see §2.10). The function returns the previous value of the step multiplier.
    

    【讨论】:

    • 不过,这已在 5.1 中删除。如何复制?
    【解决方案2】:

    在 Lua 中,可以删除像 userdata 这样的对象的唯一方法是通过垃圾收集器。你可以直接调用垃圾收集器,就像 B Mitch 写的那样(使用lua_gc(L, LUA_CGSTEP, ...)),但不能保证你的临时对象会被释放。

    解决此问题的最佳方法是避免创建临时对象。如果您需要将固定参数传递给 SetPosition 等方法,请尝试修改 API,使其也接受数字参数,避免创建临时对象,如下所示:

    myObject:SetPosition(123, 456)
    

    【讨论】:

    • 我肯定更喜欢 Lua 中的小容器对象而不是数字。在 Lua 中返回一个向量也可以使用返回多个值的函数。返回 2 个值的函数可以用作期望 2 个值的函数中的参数,这一事实使得这具有双重用途。
    【解决方案3】:

    Lua Gems 有一篇关于 Lua 程序优化的精彩文章。

    【讨论】:

      【解决方案4】:

      请记住,Lua 直到运行时才知道您是否保存了这些对象——例如,您可以将它们放在注册表中的一个表中。你甚至不应该注意到收集 1.5MB 的影响,这里还有另一个问题。

      另外,为此制作新对象真的很浪费。还记得在 Lua 中每个对象都必须动态分配,所以你调用 malloc 来......创建一个 Vector 对象来保存两个数字?编写函数以将一对数字参数作为重载。

      【讨论】:

        猜你喜欢
        • 2010-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多