Execution time of Lua script in Defold is VERY high compared to execution through terminal

Description
Running 10000000 loops in a Lua module script using LuaJIT 2.1.0-beta3 in the terminal gives 10.62 seconds.
Using the same module in Defold by requiring the same module gives execution time of 3 minutes.
Can we know what is causing this and if there is any way we can get around this? This is very crucial for our project and we would appreciate any effort from anyone answering this question.

To Reproduce
Steps to reproduce the behavior:

  1. Make a Lua module with following script:
local M = {}

local function run_loop()
    for i = 1, 10000000 do
        print(i)
    end
end

run_loop()

return M
  1. Run it in terminal using “luajit .lua” and evaluate time taken.
  2. Require same Lua module in main.script in an empty Mobile Game template Defold project and evaluate again.

Defold version:

  • Version : 1.6.2

Platforms:

  • Platforms: macOS, Android
  • OS: MacOS 13.3.1, AndroidOS
  • Device: MacBook Air M1, Any Android Device
1 Like

I think print can be problem. If you run debug build or build in editor, it will use log system for prints.

What if you replace print with some math?

10 Likes

I did as you said. I put a simple 1 + 1 inside the loop and removed the print as so. I even added a simple execution time calculator.

local M = {}

local function run_loop()
	local time_start = os.time()
	for i = 1, 100000000 do
		local a = 1 + 1
	end
	print("End time: ", os.time() - time_start)
end

run_loop()

return M

The time taken to execute has reduced by a lot.
LuaJIT through terminal → 0 second (probably has float value, but it was very fast)
Defold → 35 seconds

But as you can see, the issue still persists. Execution in Defold is taking a lot more time.

1 Like

It looks like it is the jit compilation which messes with the execution of that loop. Disable jit compilation and it is as fast as you’d expect:

if jit then jit.off() end
run_loop()
if jit then jit.on() end
4 Likes

Thank you! This worked for us. But it looks too good to be true. So I would like to know what are the downsides of doing this.

I’m also curious as to why the JIT compilation is causing this. Would appreciate it if you could briefly explain.

2 Likes

I guess switching of JIT reduces start up time for your test.
Your test is a good first step towards thinking about profiling. Of itself the test is not useful, what is actually being tested is opaque (a compiler might replace 1+1 with 2 or even remove the loop completely, who knows). Then there is relating ‘results’ to what you really want to do. Better to profile your actual game:

4 Likes