mirror of
https://github.com/go-gitea/gitea.git
synced 2026-07-24 01:40:31 +00:00
This pull request optimizes `FindEmojiSubmatchIndex` in Gitea's emoji package (`modules/emoji/emoji.go`) by replacing the `strings.Replacer`-based search with a slice-based trie and a constant-time starting-byte check (`isStartingByte`). The new implementation avoids heap allocations during the search and reduces CPU overhead when rendering Markdown, particularly for plain text that does not contain emojis. ### Verification Verified with unit tests: ```sh go test -count=1 ./modules/emoji/... ``` Benchmarks: ```sh go test -bench=. -benchmem ./modules/emoji/... ``` ### Results | Benchmark | Before | After | | ---------- | ------ | ----- | | `BenchmarkFindEmojiSubmatchIndex` | 168.3 ns/op, 2 allocs/op | 85.78 ns/op, 1 alloc/op | | `BenchmarkFindEmojiSubmatchIndexNoMatch` | 239.8 ns/op, 1 alloc/op | 105.1 ns/op, 0 allocs/op | ### Benchmark Output ```text goos: linux goarch: amd64 pkg: gitea.dev/modules/emoji cpu: Intel(R) Core(TM) i5-7400 CPU @ 3.00GHz BenchmarkFindEmojiSubmatchIndex-4 13498539 85.78 ns/op 16 B/op 1 allocs/op BenchmarkFindEmojiSubmatchIndexNoMatch-4 11220450 105.1 ns/op 0 B/op 0 allocs/op BenchmarkFindEmojiSubmatchIndexOld-4 6569360 168.3 ns/op 48 B/op 2 allocs/op BenchmarkFindEmojiSubmatchIndexOldNoMatch-4 5026116 239.8 ns/op 32 B/op 1 allocs/op ``` --------- Signed-off-by: Sudhanshu Singh <sudhanshuwriterblc@gmail.com> Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
35 lines
843 B
Go
35 lines
843 B
Go
// Copyright 2026 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package util
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestTrie(t *testing.T) {
|
|
trie := &TrieNode{}
|
|
trie.Insert("apple")
|
|
trie.Insert("apricot")
|
|
trie.Insert("banana")
|
|
trie.Insert("app")
|
|
|
|
// Test exact matches
|
|
assert.Equal(t, 5, trie.Match("apple", 0))
|
|
assert.Equal(t, 7, trie.Match("apricot", 0))
|
|
assert.Equal(t, 6, trie.Match("banana", 0))
|
|
assert.Equal(t, 3, trie.Match("app", 0))
|
|
|
|
// Test partial match (longest match priority)
|
|
assert.Equal(t, 5, trie.Match("apple-pie", 0))
|
|
|
|
// Test suffix/nested position match
|
|
assert.Equal(t, 5, trie.Match("sweet apple", 6))
|
|
|
|
// Test no match
|
|
assert.Equal(t, -1, trie.Match("orange", 0))
|
|
assert.Equal(t, -1, trie.Match("ap", 0)) // prefix exists but is not an end node
|
|
}
|