Skip to content

Commit e95ae6a

Browse files
committed
filter: lua: preallocate the next function
Reduce allocation from 4 to 2 by preallocating the lua function which is a wrapper to the Go 'next' function we receive. name old time/op new time/op delta LUAProcess-8 559ns ± 6% 459ns ± 7% -17.97% (p=0.000 n=10+10) name old alloc/op new alloc/op delta LUAProcess-8 104B ± 0% 24B ± 0% -76.92% (p=0.000 n=10+10) name old allocs/op new allocs/op delta LUAProcess-8 4.00 ± 0% 2.00 ± 0% -50.00% (p=0.000 n=10+10)
1 parent cc9244b commit e95ae6a

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

filter/lua.go

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ type LUA struct {
2525
l *lua.LState
2626
ud *lua.LUserData
2727
luaFunc lua.LValue
28+
luaNext *lua.LFunction
29+
next func(baker.Record)
2830
}
2931

3032
func NewLUA(cfg baker.FilterParams) (baker.Filter, error) {
@@ -48,6 +50,12 @@ func NewLUA(cfg baker.FilterParams) (baker.Filter, error) {
4850
ud: ud,
4951
}
5052

53+
// Preallocate the lua next function passed to the filter
54+
f.luaNext = l.NewFunction(func(L *lua.LState) int {
55+
f.next(fastcheckLuaRecord(L, 1).r)
56+
return 0
57+
})
58+
5159
runtime.SetFinalizer(f, func(f *LUA) { f.l.Close() })
5260

5361
return f, nil
@@ -56,21 +64,18 @@ func NewLUA(cfg baker.FilterParams) (baker.Filter, error) {
5664
func (t *LUA) Stats() baker.FilterStats { return baker.FilterStats{} }
5765

5866
func (t *LUA) Process(rec baker.Record, next func(baker.Record)) {
59-
luaNext := t.l.NewFunction(func(L *lua.LState) int {
60-
recordArg := fastcheckLuaRecord(L, 1)
61-
next(recordArg.r)
62-
return 0
63-
})
64-
6567
// Modify the record inside the pre-allocated user value
6668
t.ud.Value = &luaRecord{r: rec}
6769

70+
// Set the next function which is called by the lua filter to the one
71+
// we just received.
72+
t.next = next
73+
6874
err := t.l.CallByParam(lua.P{
6975
Fn: t.luaFunc,
7076
NRet: 0,
7177
Protect: true,
72-
}, t.ud,
73-
luaNext)
78+
}, t.ud, t.luaNext)
7479

7580
if err != nil {
7681
panic(err)

0 commit comments

Comments
 (0)