Skip to content

Commit 1a057ad

Browse files
committed
perf(key): Use string builder for path concatenation
By leveraging the string builder and establishing the capacity of the underlying slice, we can reduce a few unnecessary allocations per event.
1 parent 388a037 commit 1a057ad

2 files changed

Lines changed: 47 additions & 3 deletions

File tree

pkg/util/key/key.go

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,12 @@
2222
package key
2323

2424
import (
25-
"github.com/rabbitstack/fibratus/pkg/sys"
26-
"golang.org/x/sys/windows/registry"
2725
"path/filepath"
2826
"regexp"
2927
"strings"
28+
29+
"github.com/rabbitstack/fibratus/pkg/sys"
30+
"golang.org/x/sys/windows/registry"
3031
)
3132

3233
var (
@@ -202,6 +203,18 @@ func Format(key string) (Key, string) {
202203
return Invalid, key
203204
}
204205

206+
// ConcatPaths concatenates root and subkey registry paths.
207+
func ConcatPaths(root, path string) string {
208+
var b strings.Builder
209+
b.Grow(len(root) + len(path) + 1)
210+
if root != "" {
211+
b.WriteString(root)
212+
b.WriteByte('\\')
213+
}
214+
b.WriteString(path)
215+
return b.String()
216+
}
217+
205218
func subkey(key string, prefix string) string {
206219
if len(key) > len(prefix) {
207220
return key[len(prefix)+1:]

pkg/util/key/key_test.go

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,12 @@
2222
package key
2323

2424
import (
25+
"testing"
26+
2527
"github.com/stretchr/testify/assert"
2628
"github.com/stretchr/testify/require"
2729
"golang.org/x/sys/windows"
2830
"golang.org/x/sys/windows/registry"
29-
"testing"
3031
)
3132

3233
func init() {
@@ -182,3 +183,33 @@ func TestReadValue(t *testing.T) {
182183
})
183184
}
184185
}
186+
187+
func TestConcatPaths(t *testing.T) {
188+
var tests = []struct {
189+
root string
190+
subkey string
191+
expected string
192+
}{
193+
{
194+
root: "HKEY_LOCAL_MACHINE",
195+
subkey: `Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\Capabilities`,
196+
expected: `HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\Capabilities`,
197+
},
198+
{
199+
root: "",
200+
subkey: `Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\Capabilities`,
201+
expected: `Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\Capabilities`,
202+
},
203+
{
204+
root: "HKEY_LOCAL_MACHINE",
205+
subkey: "",
206+
expected: "HKEY_LOCAL_MACHINE\\",
207+
},
208+
}
209+
210+
for _, tt := range tests {
211+
t.Run(tt.root+tt.subkey, func(t *testing.T) {
212+
assert.Equal(t, tt.expected, ConcatPaths(tt.root, tt.subkey))
213+
})
214+
}
215+
}

0 commit comments

Comments
 (0)