VCVRack / VCV-Prototype

Other
130 stars 23 forks source link

Improves the LuaJIT performance by using luaL_openlibs to initialize the VM #26

Closed modlfo closed 4 years ago

modlfo commented 4 years ago

As I mentioned in my other pull request. This change doubles the performance of my complex Lua code. In order to forbid the unsafe libraries, like io and os, they are set to nil just after initializing the VM.

I also set to nil the function require that way no other libraries can be loaded.

modlfo commented 4 years ago

I found the reason for the speedup. The JIT library needs to be loaded in order to turn the JIT engine on, otherwise it will be off. I have loaded the library and then set it to nil so it cannot be used in the script.

AndrewBelt commented 4 years ago

Hahaha, I didn't even have JIT enabled??

teknico commented 4 years ago

Hahaha, I didn't even have JIT enabled??

It did seem to run slower than Javascript when I tried it.

modlfo commented 4 years ago

There's still something strange. In my benchmarks, LuaJIT most of the times performs almost as fast as C++. The main case when LuaJIT is slower is when the program has large arrays. The main difference, in the case of my benchmarks, is that the LuaJIT executable runs the whole tests (it's not embedded in other executable).

I will keep investigating when I have some time.

modlfo commented 4 years ago

I have the sensation that the performance hit is in the reading and writing of the block information. Some years ago I was working on my AudioEngine based on LuaJIT and seems like I used the LuaJIT FFI to have fast access to the audio buffers.

https://github.com/modlfo/AudioEngine/blob/master/AudioEngine/LuaScripts/processor.lua

I will try to make a version that uses the FFI to access directly the ProcessBlock.

JerrySievert commented 4 years ago

I have the sensation that the performance hit is in the reading and writing of the block information. Some years ago I was working on my AudioEngine based on LuaJIT and seems like I used the LuaJIT FFI to have fast access to the audio buffers.

that is typically the issue with javascript engines as well. the c++/interpreter membrane ends up being the expensive part of the equation.

modlfo commented 4 years ago

Using the LuaJIT FFI to access the ProcessBlock my plugin went from consuming 25% to 5%. Just for reference, the C++ version consumes 2%.

I will prepare a new pull request for this improvement.

AndrewBelt commented 4 years ago

For turning JIT on, is luaJIT_setmode the function you want? Probably luaopen_jit and luaL_openlibs call this function, but if we don't want the jit. library, maybe calling luaJIT_setmode manually is the best way to do it.