Skip to content

Commit ad75dba

Browse files
Desoursfan5
authored andcommittedMar 27, 2019
Optimize core.after in a simple way (#8351)
1 parent 42e1a12 commit ad75dba

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed
 

Diff for: ‎builtin/common/after.lua

+13-5
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,41 @@
11
local jobs = {}
22
local time = 0.0
3+
local time_next = math.huge
34

45
core.register_globalstep(function(dtime)
56
time = time + dtime
67

7-
if #jobs < 1 then
8+
if time < time_next then
89
return
910
end
1011

12+
time_next = math.huge
13+
1114
-- Iterate backwards so that we miss any new timers added by
12-
-- a timer callback, and so that we don't skip the next timer
13-
-- in the list if we remove one.
15+
-- a timer callback.
1416
for i = #jobs, 1, -1 do
1517
local job = jobs[i]
1618
if time >= job.expire then
1719
core.set_last_run_mod(job.mod_origin)
1820
job.func(unpack(job.arg))
19-
table.remove(jobs, i)
21+
local jobs_l = #jobs
22+
jobs[i] = jobs[jobs_l]
23+
jobs[jobs_l] = nil
24+
elseif job.expire < time_next then
25+
time_next = job.expire
2026
end
2127
end
2228
end)
2329

2430
function core.after(after, func, ...)
2531
assert(tonumber(after) and type(func) == "function",
2632
"Invalid minetest.after invocation")
33+
local expire = time + after
2734
jobs[#jobs + 1] = {
2835
func = func,
29-
expire = time + after,
36+
expire = expire,
3037
arg = {...},
3138
mod_origin = core.get_last_run_mod()
3239
}
40+
time_next = math.min(time_next, expire)
3341
end

0 commit comments

Comments
 (0)
Please sign in to comment.