-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperformance_test.go
More file actions
60 lines (51 loc) · 1.43 KB
/
Copy pathperformance_test.go
File metadata and controls
60 lines (51 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"regexp"
"strings"
"testing"
)
// read the write-up: https://abanoubhanna.com/posts/regexp-vs-string-manipulation/
// Original implementation using regexp
func generateCommandRegexp(template, pkgName string) string {
re := regexp.MustCompile(`\bx\b`)
return re.ReplaceAllStringFunc(template, func(s string) string {
return pkgName
})
}
// Pre-compiled regexp implementation (fairer comparison)
var cmdRe = regexp.MustCompile(`\bx\b`)
func generateCommandRegexpCompiled(template, pkgName string) string {
return cmdRe.ReplaceAllStringFunc(template, func(s string) string {
return pkgName
})
}
// using string manipulation
func generateCommandString(template, pkgName string) string {
cmdStr := template
// if template ends with ".x" or " x" remove x and add pkgName
if strings.HasSuffix(template, ".x") || strings.HasSuffix(template, " x") {
cmdStr = strings.TrimSuffix(template, "x") + pkgName
}
return cmdStr
}
func BenchmarkRegexpReplacement(b *testing.B) {
template := "apt install -y x"
pkgName := "vim"
for b.Loop() {
generateCommandRegexp(template, pkgName)
}
}
func BenchmarkRegexpPrecompiledReplacement(b *testing.B) {
template := "apt install -y x"
pkgName := "vim"
for b.Loop() {
generateCommandRegexpCompiled(template, pkgName)
}
}
func BenchmarkStringReplacement(b *testing.B) {
template := "apt install -y x"
pkgName := "vim"
for b.Loop() {
generateCommandString(template, pkgName)
}
}