LuaInterface C#: dostring vs dofile. Is it worth loading a script that will be called numerous times into memory?

StackOverflow https://stackoverflow.com/questions/14958968

  •  10-03-2022
  •  | 
  •  

Question

Can anyone tell me if I can reasonably expect any performance gain by loading a lua script that will be called repetitively into memory for execution through LuaInterface's dostring() functionality rather than dofile()?

Am I correct in assuming this will perform better by reducing file-system access each iteration?

Is there some way to cache the script within the Lua VM?

Was it helpful?

Solution

If you want to execute some lua code for many times, the better way is using LoadFile OR LoadString. Load lua code as a LuaFunction, like:

LuaFunction lf = xxx.LoadString("some lua code");   // xxx is an instance of LuaInterface
lf.Call();   // you can also deliver some arguments

This is much faster than DoFile AND DoString. Because it needs just one time compiling.

OTHER TIPS

Am I correct in assuming this will perform better by reducing file-system access each iteration?

In general, you should benchmark rather than assume, but this is pretty cut and dried: "disk IO, compile, execute" vs "execute". Of course the latter is going to be faster.

Is there some way to cache the script within the Lua VM?

Whether you dofile or dostring any globals your script produces will be available for you to read/call. If you want to avoid your scripts modifying the VM's global namespace, you can expose an API routine (in the host) that your script can call to register a callback.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top