test(bench): add allocation benchmarks for client/transport/dispatch hot paths

Hermetic benchmarks (no network) covering Call encode+decode, webhook ServeHTTP body parse, and Router dispatch (command/regex/filter). Use Go 1.24+ b.Loop() idiom. .benchstats/baseline.txt pins the pre-optimisation numbers for benchstat comparisons.
This commit is contained in:
2026-05-10 02:31:46 +01:00
parent 9cfe193e2e
commit 728b28b0c5
4 changed files with 241 additions and 0 deletions
+89
View File
@@ -0,0 +1,89 @@
package dispatch
import (
"context"
"testing"
"github.com/lukaszraczylo/go-telegram/api"
"github.com/lukaszraczylo/go-telegram/client"
)
func BenchmarkRouter_DispatchCommand(b *testing.B) {
r := New(client.New("t"))
r.OnCommand("/start", func(c *Context, m *api.Message) error { return nil })
u := cmdMessage("/start hello")
ctx := context.Background()
b.ReportAllocs()
for b.Loop() {
c := NewContext(ctx, r.bot, &u)
_ = r.dispatch(c, &u)
}
}
func BenchmarkRouter_DispatchTextRegex(b *testing.B) {
r := New(client.New("t"))
r.OnText("^hello.*", func(c *Context, m *api.Message) error { return nil })
u := api.Update{
UpdateID: 1,
Message: &api.Message{
MessageID: 1, Date: 0,
Chat: api.Chat{ID: 1, Type: api.ChatTypePrivate},
Text: "hello world",
},
}
ctx := context.Background()
b.ReportAllocs()
for b.Loop() {
c := NewContext(ctx, r.bot, &u)
_ = r.dispatch(c, &u)
}
}
func BenchmarkRouter_DispatchFilter(b *testing.B) {
r := New(client.New("t"))
r.OnMessageFilter(
func(m *api.Message) bool { return m != nil && m.Text == "ping" },
func(c *Context, m *api.Message) error { return nil },
)
u := api.Update{
UpdateID: 1,
Message: &api.Message{
MessageID: 1, Date: 0,
Chat: api.Chat{ID: 1, Type: api.ChatTypePrivate},
Text: "ping",
},
}
ctx := context.Background()
b.ReportAllocs()
for b.Loop() {
c := NewContext(ctx, r.bot, &u)
_ = r.dispatch(c, &u)
}
}
func BenchmarkRouter_NewContext(b *testing.B) {
bot := client.New("t")
u := &api.Update{UpdateID: 1}
ctx := context.Background()
b.ReportAllocs()
for b.Loop() {
_ = NewContext(ctx, bot, u)
}
}
func BenchmarkExtractCommand(b *testing.B) {
text := "/start@BotName hello world"
cmdLen := len("/start@BotName")
m := &api.Message{
MessageID: 1, Date: 0,
Chat: api.Chat{ID: 1, Type: api.ChatTypePrivate},
Text: text,
Entities: []api.MessageEntity{
{Type: api.MessageEntityTypeBotCommand, Offset: 0, Length: int64(cmdLen)},
},
}
b.ReportAllocs()
for b.Loop() {
_, _, _ = extractCommand(m)
}
}