wails/v3/pkg/application/systemtray_bench_test.go
Lea Anthony a06d55804c
perf(v3): optimize JSON processing and reduce allocations in hot paths (#4843)
* perf(v3): optimize JSON processing and reduce allocations in hot paths

- Switch to goccy/go-json for method binding, events, and HTTP transport
  (21-63% faster, 40-60% less memory for method calls)
- Optimize BoundMethod struct layout to reduce padding (144 -> 136 bytes)
- Cache isVariadic flag at registration to avoid reflect call per invocation
- Use stack-allocated buffer for method arguments (<=8 args)
- Optimize result collection to avoid slice allocation for single return values
- Use sync.Map for MIME cache to improve concurrent read performance
- Use buffer pool for HTTP transport request body reading
- Lazily allocate CloseNotify channel in content type sniffer
- Remove debug CSS logging from asset server
- Add comprehensive benchmark tests (build tag: bench)

Performance improvements for BoundMethod.Call:
- SimpleCall:   1290ns -> 930ns (28% faster), 240B -> 80B (67% less memory)
- ComplexCall:  10500ns -> 3900ns (63% faster), 1192B -> 1020B (14% less)
- VariadicCall: 3460ns -> 1600ns (54% faster), 512B -> 289B (44% less)

* perf(v3): add max size limit to buffer pool to prevent memory bloat

Buffers larger than 512KB are not returned to the pool, allowing GC
to reclaim memory after large requests (e.g., base64 encoded images).

* perf(v3): remove mimetype library dependency, saving ~208KB binary size

- Replace github.com/wailsapp/mimetype with expanded extension map + stdlib
- Expand MIME type map from 16 to 50+ common web formats (fonts, audio, video, etc.)
- Add comprehensive test suite validating MIME detection for all web formats
- Use http.DetectContentType as fallback for unknown extensions
- Actual binary size reduction: 1.2MB (11MB -> 9.8MB in test app)

* perf(v3): migrate all runtime code to goccy/go-json

Migrate remaining encoding/json usages to goccy/go-json in:
- pkg/application (android, darwin, ios, single_instance, webview_window)
- pkg/services (kvstore, notifications on all platforms)
- internal/assetserver/webview (request/response handling)
- internal/runtime and internal/capabilities

Note: encoding/json (110KB) remains in binary because:
1. goccy/go-json imports it for interface compatibility (json.Marshaler, etc.)
2. log/slog (stdlib) uses it for JSON output

The performance benefit is in the hot paths which now use the faster library.

* perf(v3): replace gopkg.in/ini.v1 with minimal .desktop file parser

Replace the gopkg.in/ini.v1 dependency with a purpose-built minimal parser
for Linux .desktop files.

The new parser:
- Only extracts the Exec key from [Desktop Entry] section (all we need)
- Follows the Desktop Entry Specification
- Has comprehensive test coverage (40 tests) including:
  - All major file managers (Nautilus, Dolphin, Thunar, PCManFM, Caja, Nemo)
  - Edge cases (UTF-8, special chars, comments, empty files, etc.)
  - Buffer limit handling

Binary size reduction: 45KB (10.22MB -> 10.18MB)

* perf(v3): remove samber/lo from runtime code, saving ~310KB binary size

Replace samber/lo with Go 1.21+ stdlib slices package and minimal internal
helpers in all runtime code paths. This removes 80 transitive dependencies
from the production binary.

Changes:
- Create internal/sliceutil package with Unique and FindMapKey helpers
- Replace lo.Without with slices.DeleteFunc in event handling
- Replace lo.Ternary with inline if/else in Windows code
- Replace lo.Uniq with sliceutil.Unique for feature flags
- Replace lo.FindKey with sliceutil.FindMapKey for method aliases
- Replace lo.Filter with slices.DeleteFunc in event listeners
- Replace lo.Must with inline panic in w32 package

Binary size: 10.18MB -> 9.87MB (~310KB / 3% reduction)

Note: CLI tools still use samber/lo since they don't affect
production binary size. The application_debug.go file also
retains lo usage as it has //go:build !production tag.

* fix: address CodeRabbit review comments

- Use application/x-typescript MIME type (not IANA-registered text/typescript)
- Fix potential panic in mimetype_stdlib_test.go for short MIME strings
- Use cached isVariadic flag in bindings_optimized_bench_test.go

* fix: initialize goccy/go-json decoder early to fix Windows test failure

On Windows, goccy/go-json's type address calculation can fail if the
decoder is first invoked during test execution rather than at init time.
Force early initialization by unmarshaling a []int during package init.

See: https://github.com/goccy/go-json/issues/474

* 📝 Add docstrings to `v3/performance-improvements` (#4844)

* fix: initialize goccy/go-json decoder early to fix Windows test failure

On Windows, goccy/go-json's type address calculation can fail if the
decoder is first invoked during test execution rather than at init time.
Force early initialization by unmarshaling a []int during package init.

See: https://github.com/goccy/go-json/issues/474

* 📝 Add docstrings to `v3/performance-improvements`

Docstrings generation was requested by @leaanthony.

* https://github.com/wailsapp/wails/pull/4843#issuecomment-3703472562

The following files were modified:

* `v3/internal/assetserver/common.go`
* `v3/internal/assetserver/content_type_sniffer.go`
* `v3/internal/assetserver/mimecache.go`
* `v3/internal/fileexplorer/desktopfile.go`
* `v3/internal/fileexplorer/fileexplorer_linux.go`
* `v3/internal/sliceutil/sliceutil.go`
* `v3/pkg/application/application_ios.go`
* `v3/pkg/application/bindings.go`
* `v3/pkg/application/ios_runtime_ios.go`
* `v3/pkg/w32/window.go`

---------

Co-authored-by: Lea Anthony <lea.anthony@gmail.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-02 07:03:36 +11:00

374 lines
8 KiB
Go

//go:build bench
package application
import (
"testing"
"time"
)
// Note: SystemTray benchmarks are limited since actual system tray operations
// require platform-specific GUI initialization. These benchmarks focus on
// the Go-side logic that can be tested without a running GUI.
// BenchmarkSystemTrayCreation measures the cost of creating SystemTray instances
func BenchmarkSystemTrayCreation(b *testing.B) {
for b.Loop() {
tray := newSystemTray(1)
_ = tray
}
}
// BenchmarkSystemTrayConfiguration measures configuration operations
func BenchmarkSystemTrayConfiguration(b *testing.B) {
b.Run("SetLabel", func(b *testing.B) {
tray := newSystemTray(1)
// impl is nil, so this just sets the field
for b.Loop() {
tray.SetLabel("Test Label")
}
})
b.Run("SetTooltip", func(b *testing.B) {
tray := newSystemTray(1)
for b.Loop() {
tray.SetTooltip("Test Tooltip")
}
})
b.Run("SetIcon", func(b *testing.B) {
tray := newSystemTray(1)
icon := make([]byte, 1024) // 1KB icon data
for b.Loop() {
tray.SetIcon(icon)
}
})
b.Run("SetDarkModeIcon", func(b *testing.B) {
tray := newSystemTray(1)
icon := make([]byte, 1024)
for b.Loop() {
tray.SetDarkModeIcon(icon)
}
})
b.Run("SetTemplateIcon", func(b *testing.B) {
tray := newSystemTray(1)
icon := make([]byte, 1024)
for b.Loop() {
tray.SetTemplateIcon(icon)
}
})
b.Run("SetIconPosition", func(b *testing.B) {
tray := newSystemTray(1)
for b.Loop() {
tray.SetIconPosition(NSImageLeading)
}
})
b.Run("ChainedConfiguration", func(b *testing.B) {
icon := make([]byte, 1024)
for b.Loop() {
tray := newSystemTray(1)
tray.SetIcon(icon).
SetDarkModeIcon(icon).
SetIconPosition(NSImageLeading)
}
})
}
// BenchmarkClickHandlerExecution measures handler registration and invocation
func BenchmarkClickHandlerExecution(b *testing.B) {
b.Run("RegisterClickHandler", func(b *testing.B) {
for b.Loop() {
tray := newSystemTray(1)
tray.OnClick(func() {})
}
})
b.Run("RegisterAllHandlers", func(b *testing.B) {
for b.Loop() {
tray := newSystemTray(1)
tray.OnClick(func() {})
tray.OnRightClick(func() {})
tray.OnDoubleClick(func() {})
tray.OnRightDoubleClick(func() {})
tray.OnMouseEnter(func() {})
tray.OnMouseLeave(func() {})
}
})
b.Run("InvokeClickHandler", func(b *testing.B) {
tray := newSystemTray(1)
counter := 0
tray.OnClick(func() {
counter++
})
b.ResetTimer()
for b.Loop() {
if tray.clickHandler != nil {
tray.clickHandler()
}
}
})
b.Run("InvokeAllHandlers", func(b *testing.B) {
tray := newSystemTray(1)
counter := 0
handler := func() { counter++ }
tray.OnClick(handler)
tray.OnRightClick(handler)
tray.OnDoubleClick(handler)
tray.OnRightDoubleClick(handler)
tray.OnMouseEnter(handler)
tray.OnMouseLeave(handler)
b.ResetTimer()
for b.Loop() {
if tray.clickHandler != nil {
tray.clickHandler()
}
if tray.rightClickHandler != nil {
tray.rightClickHandler()
}
if tray.doubleClickHandler != nil {
tray.doubleClickHandler()
}
if tray.rightDoubleClickHandler != nil {
tray.rightDoubleClickHandler()
}
if tray.mouseEnterHandler != nil {
tray.mouseEnterHandler()
}
if tray.mouseLeaveHandler != nil {
tray.mouseLeaveHandler()
}
}
})
}
// BenchmarkWindowAttachment measures window attachment configuration
func BenchmarkWindowAttachment(b *testing.B) {
b.Run("AttachWindow", func(b *testing.B) {
// We can't create real windows, but we can test the attachment logic
for b.Loop() {
tray := newSystemTray(1)
// AttachWindow accepts nil gracefully
tray.AttachWindow(nil)
}
})
b.Run("WindowOffset", func(b *testing.B) {
tray := newSystemTray(1)
for b.Loop() {
tray.WindowOffset(10)
}
})
b.Run("WindowDebounce", func(b *testing.B) {
tray := newSystemTray(1)
for b.Loop() {
tray.WindowDebounce(200 * time.Millisecond)
}
})
b.Run("ChainedAttachment", func(b *testing.B) {
for b.Loop() {
tray := newSystemTray(1)
tray.AttachWindow(nil).
WindowOffset(10).
WindowDebounce(200 * time.Millisecond)
}
})
}
// BenchmarkMenuConfiguration measures menu setup operations
func BenchmarkMenuConfiguration(b *testing.B) {
b.Run("SetNilMenu", func(b *testing.B) {
tray := newSystemTray(1)
for b.Loop() {
tray.SetMenu(nil)
}
})
b.Run("SetSimpleMenu", func(b *testing.B) {
menu := NewMenu()
menu.Add("Item 1")
menu.Add("Item 2")
menu.Add("Item 3")
tray := newSystemTray(1)
b.ResetTimer()
for b.Loop() {
tray.SetMenu(menu)
}
})
b.Run("SetComplexMenu", func(b *testing.B) {
menu := NewMenu()
for i := 0; i < 20; i++ {
menu.Add("Item")
}
submenu := NewMenu()
for i := 0; i < 10; i++ {
submenu.Add("Subitem")
}
tray := newSystemTray(1)
b.ResetTimer()
for b.Loop() {
tray.SetMenu(menu)
}
})
}
// BenchmarkIconSizes measures icon handling with different sizes
func BenchmarkIconSizes(b *testing.B) {
sizes := []struct {
name string
size int
}{
{"16x16", 16 * 16 * 4}, // 1KB - small icon
{"32x32", 32 * 32 * 4}, // 4KB - medium icon
{"64x64", 64 * 64 * 4}, // 16KB - large icon
{"128x128", 128 * 128 * 4}, // 64KB - retina icon
{"256x256", 256 * 256 * 4}, // 256KB - high-res icon
}
for _, size := range sizes {
b.Run(size.name, func(b *testing.B) {
icon := make([]byte, size.size)
tray := newSystemTray(1)
b.ResetTimer()
for b.Loop() {
tray.SetIcon(icon)
}
})
}
}
// BenchmarkWindowAttachConfigInit measures WindowAttachConfig initialization
func BenchmarkWindowAttachConfigInit(b *testing.B) {
b.Run("DefaultConfig", func(b *testing.B) {
for b.Loop() {
config := WindowAttachConfig{
Window: nil,
Offset: 0,
Debounce: 200 * time.Millisecond,
}
_ = config
}
})
b.Run("FullConfig", func(b *testing.B) {
for b.Loop() {
config := WindowAttachConfig{
Window: nil,
Offset: 10,
Debounce: 300 * time.Millisecond,
justClosed: false,
hasBeenShown: true,
}
_ = config
}
})
}
// BenchmarkSystemTrayShowHide measures show/hide state changes
// Note: These operations are no-ops when impl is nil, but we measure the check overhead
func BenchmarkSystemTrayShowHide(b *testing.B) {
b.Run("Show", func(b *testing.B) {
tray := newSystemTray(1)
for b.Loop() {
tray.Show()
}
})
b.Run("Hide", func(b *testing.B) {
tray := newSystemTray(1)
for b.Loop() {
tray.Hide()
}
})
b.Run("ToggleShowHide", func(b *testing.B) {
tray := newSystemTray(1)
for b.Loop() {
tray.Show()
tray.Hide()
}
})
}
// BenchmarkIconPositionConstants measures icon position constant access
func BenchmarkIconPositionConstants(b *testing.B) {
positions := []IconPosition{
NSImageNone,
NSImageOnly,
NSImageLeft,
NSImageRight,
NSImageBelow,
NSImageAbove,
NSImageOverlaps,
NSImageLeading,
NSImageTrailing,
}
b.Run("SetAllPositions", func(b *testing.B) {
tray := newSystemTray(1)
for b.Loop() {
for _, pos := range positions {
tray.SetIconPosition(pos)
}
}
})
}
// BenchmarkLabelOperations measures label getter/setter performance
func BenchmarkLabelOperations(b *testing.B) {
b.Run("SetLabel", func(b *testing.B) {
tray := newSystemTray(1)
for b.Loop() {
tray.SetLabel("System Tray Label")
}
})
b.Run("GetLabel", func(b *testing.B) {
tray := newSystemTray(1)
tray.SetLabel("System Tray Label")
b.ResetTimer()
for b.Loop() {
_ = tray.Label()
}
})
b.Run("SetGetLabel", func(b *testing.B) {
tray := newSystemTray(1)
for b.Loop() {
tray.SetLabel("Label")
_ = tray.Label()
}
})
}
// BenchmarkDefaultClickHandler measures the default click handler logic
func BenchmarkDefaultClickHandler(b *testing.B) {
b.Run("NoAttachedWindow", func(b *testing.B) {
tray := newSystemTray(1)
// With no menu and no attached window, defaultClickHandler returns early
for b.Loop() {
tray.defaultClickHandler()
}
})
b.Run("WithNilWindow", func(b *testing.B) {
tray := newSystemTray(1)
tray.attachedWindow.Window = nil
for b.Loop() {
tray.defaultClickHandler()
}
})
}