107 lines
1.9 KiB
Go
107 lines
1.9 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-Param0", 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.LookupNoAlloc("GET", "/:id", noop)
|
||
|
}
|
||
|
})
|
||
|
}
|
||
|
|
||
|
func BenchmarkGithub(b *testing.B) {
|
||
|
routes := routes("routes.txt")
|
||
|
r := router.New[string]()
|
||
|
|
||
|
for _, route := range routes {
|
||
|
r.Add(route.Method, route.Path, "")
|
||
|
}
|
||
|
|
||
|
b.Run("Len7-Param0", func(b *testing.B) {
|
||
|
for i := 0; i < b.N; i++ {
|
||
|
r.LookupNoAlloc("GET", "/issues", noop)
|
||
|
}
|
||
|
})
|
||
|
|
||
|
b.Run("Len7-Param1", func(b *testing.B) {
|
||
|
for i := 0; i < b.N; i++ {
|
||
|
r.LookupNoAlloc("GET", "/gists/:id", noop)
|
||
|
}
|
||
|
})
|
||
|
|
||
|
b.Run("Len7-Param2", 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
|
||
|
}
|
||
|
|
||
|
// Routes 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
|
||
|
}
|
||
|
|
||
|
// Lines is a utility function to 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) {}
|