Skip to content

Commit cc9244b

Browse files
committed
filter: lua: reduce allocation
Suppress one allocation, reducing their number from 5 to 4, by pre-allocating the userdata we use to wrap the record passed to the lua filter. name old time/op new time/op delta LUAProcess-8 638ns ± 4% 559ns ± 6% -12.31% (p=0.000 n=10+10) name old alloc/op new alloc/op delta LUAProcess-8 152B ± 0% 104B ± 0% -31.58% (p=0.000 n=10+10) name old allocs/op new allocs/op delta LUAProcess-8 5.00 ± 0% 4.00 ± 0% -20.00% (p=0.000 n=10+10)
1 parent 7b1a1d7 commit cc9244b

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

filter/lua.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ type LUAConfig struct {
2323

2424
type LUA struct {
2525
l *lua.LState
26+
ud *lua.LUserData
2627
luaFunc lua.LValue
2728
}
2829

@@ -37,9 +38,14 @@ func NewLUA(cfg baker.FilterParams) (baker.Filter, error) {
3738
// TODO: check function exists
3839
luaFunc := l.GetGlobal(dcfg.FilterName)
3940

41+
// Preallocate the userdata we use to wrap the record passed to the filter.
42+
ud := l.NewUserData()
43+
l.SetMetatable(ud, l.GetTypeMetatable(luaRecordTypeName))
44+
4045
f := &LUA{
4146
luaFunc: luaFunc,
4247
l: l,
48+
ud: ud,
4349
}
4450

4551
runtime.SetFinalizer(f, func(f *LUA) { f.l.Close() })
@@ -56,11 +62,14 @@ func (t *LUA) Process(rec baker.Record, next func(baker.Record)) {
5662
return 0
5763
})
5864

65+
// Modify the record inside the pre-allocated user value
66+
t.ud.Value = &luaRecord{r: rec}
67+
5968
err := t.l.CallByParam(lua.P{
6069
Fn: t.luaFunc,
6170
NRet: 0,
6271
Protect: true,
63-
}, recordToLua(t.l, rec),
72+
}, t.ud,
6473
luaNext)
6574

6675
if err != nil {

0 commit comments

Comments
 (0)