137 lines
2.5 KiB
Go
137 lines
2.5 KiB
Go
package router_test
|
|
|
|
import (
|
|
"bufio"
|
|
"os"
|
|
"strings"
|
|
"testing"
|
|
|
|
router "git.sharkk.net/Go/Router"
|
|
)
|
|
|
|
func BenchmarkBlog(b *testing.B) {
|
|
routes := routes("blog.txt")
|
|
r := router.New[string]()
|
|
|
|
for _, route := range routes {
|
|
r.Add(route.Method, route.Path, "")
|
|
}
|
|
|
|
b.Run("Len1-Params0", func(b *testing.B) {
|
|
for i := 0; i < b.N; i++ {
|
|
r.Lookup("GET", "/")
|
|
}
|
|
})
|
|
|
|
b.Run("Len1-Params0-NoAlloc", func(b *testing.B) {
|
|
for i := 0; i < b.N; i++ {
|
|
r.LookupNoAlloc("GET", "/", noop)
|
|
}
|
|
})
|
|
|
|
b.Run("Len1-Param1", func(b *testing.B) {
|
|
for i := 0; i < b.N; i++ {
|
|
r.Lookup("GET", "/:id")
|
|
}
|
|
})
|
|
|
|
b.Run("Len1-Param1-NoAlloc", func(b *testing.B) {
|
|
for i := 0; i < b.N; i++ {
|
|
r.LookupNoAlloc("GET", "/:id", noop)
|
|
}
|
|
})
|
|
}
|
|
|
|
func BenchmarkGithub(b *testing.B) {
|
|
routes := routes("github.txt")
|
|
r := router.New[string]()
|
|
|
|
for _, route := range routes {
|
|
r.Add(route.Method, route.Path, "")
|
|
}
|
|
|
|
b.Run("Len7-Params0", func(b *testing.B) {
|
|
for i := 0; i < b.N; i++ {
|
|
r.Lookup("GET", "/issues")
|
|
}
|
|
})
|
|
|
|
b.Run("Len7-Params0-NoAlloc", func(b *testing.B) {
|
|
for i := 0; i < b.N; i++ {
|
|
r.LookupNoAlloc("GET", "/issues", noop)
|
|
}
|
|
})
|
|
|
|
b.Run("Len7-Params1", func(b *testing.B) {
|
|
for i := 0; i < b.N; i++ {
|
|
r.Lookup("GET", "/gists/:id")
|
|
}
|
|
})
|
|
|
|
b.Run("Len7-Params1-NoAlloc", func(b *testing.B) {
|
|
for i := 0; i < b.N; i++ {
|
|
r.LookupNoAlloc("GET", "/gists/:id", noop)
|
|
}
|
|
})
|
|
|
|
b.Run("Len7-Params3", func(b *testing.B) {
|
|
for i := 0; i < b.N; i++ {
|
|
r.Lookup("GET", "/repos/:owner/:repo/issues")
|
|
}
|
|
})
|
|
|
|
b.Run("Len7-Params3-NoAlloc", func(b *testing.B) {
|
|
for i := 0; i < b.N; i++ {
|
|
r.LookupNoAlloc("GET", "/repos/:owner/:repo/issues", noop)
|
|
}
|
|
})
|
|
}
|
|
|
|
// Route represents a single line in the router test file.
|
|
type Route struct {
|
|
Method string
|
|
Path string
|
|
}
|
|
|
|
// Loads all routes from a text file.
|
|
func routes(fileName string) []Route {
|
|
var routes []Route
|
|
|
|
for line := range lines(fileName) {
|
|
line = strings.TrimSpace(line)
|
|
parts := strings.Split(line, " ")
|
|
routes = append(routes, Route{
|
|
Method: parts[0],
|
|
Path: parts[1],
|
|
})
|
|
}
|
|
|
|
return routes
|
|
}
|
|
|
|
// Easily read every line in a text file.
|
|
func lines(fileName string) <-chan string {
|
|
lines := make(chan string)
|
|
|
|
go func() {
|
|
defer close(lines)
|
|
file, err := os.Open(fileName)
|
|
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
defer file.Close()
|
|
scanner := bufio.NewScanner(file)
|
|
|
|
for scanner.Scan() {
|
|
lines <- scanner.Text()
|
|
}
|
|
}()
|
|
|
|
return lines
|
|
}
|
|
|
|
// noop serves as an empty addParameter function.
|
|
func noop(string, string) {}
|