简体   繁体   中英

Why is MoonSharp DoString leaking memory?

I'm using MoonSharp (1.6.0, just updated, had the problem before it too) under .NET 4.6. I have the following C# code:

public class LuaCore {
    public static Script script = new Script();
    public static DynValue Call(string func)
    {
        return script.DoString(func);
    }
}

It seems like whenever I call LuaCore.Call("any code") additional ~1.5 kilobytes are used by the program. This also happens then the any code is stuff = nil , hence "any code".
When this is called about ~3500 times per second, an additional 25 megabytes are used every five seconds, and the call per second is depending on the power of the machine. Since multiple calls would be used per update, the memory usage of the program would also increase faster (tested this). After 5 minutes, I get an OutOfMemoryException (with 1.4GB used).
I took a snapshot of the heap with the app using 1.5GB of ram. It seems that the interpreter is storing each source code that was called, or it looks like that with VS's diagnostic tools.
快照中的内存堆

Why is MoonSharp storing that much data with each call?

Simple answer : you are (likely) calling the wrong API for what you are trying to do. DoString loads the specified code inside the specified Script context and runs it. If you pass the same code over and over you are just loading more and more copies of it.

So there are two options, depending on what you are trying to achieve:

  1. You are using LuaCore.Call to invoke a script which is different everytime : use Script.RunString(code) - it's a static method and doesn't preserve any state from one run to another
  2. You are using LuaCore.Call to invoke the same script over and over : Call DynValue ret = script.LoadString(code) once and then script.Call(ret) over and over.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM