3

I am building a Rest API with fasthttp package. I have a test route that I am using to measure performance:

package main

import (
    "github.com/valyala/fasthttp"
    "runtime"
)

func main() {

    runtime.GOMAXPROCS(8)
    m := func(ctx *fasthttp.RequestCtx) {
        switch string(ctx.Path()) {
        case "/test":
            test(ctx)
        default:
            ctx.Error("not found", fasthttp.StatusNotFound)
        }
    }

    fasthttp.ListenAndServe(":80", m)
}

func test(ctx *fasthttp.RequestCtx) {
    println("HERE")
}

If I send a request to this route it takes over 10 seconds to get to the println("HERE") in the test function.

I have built a comparable endpoint in Node.js and this exact same function and route takes 126 milliseconds.
Why in the world does it take so long just to call the function that this route points to in Go?

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
jrkt
  • 2,615
  • 5
  • 28
  • 48
  • I've just tested with your exact code, it takes almost no time (below 1 second) in reaching the `println("HERE")`. How excactly did you setup your test? – Koala Yeung Oct 06 '16 at 04:30
  • try my samples and post(add comment) the code (2) output –  Oct 06 '16 at 04:34

1 Answers1

4

For me it takes just 7.9454545s for 100000 http.Head (79.454545us per http.Head, with just 2 Core CPU in 77% Load when running these 1 and 2 codes).

You don't need runtime.GOMAXPROCS(8), and use fmt.Println() instead of println()

1- Try this:

package main

import (
    "fmt"

    "github.com/valyala/fasthttp"
)

func main() {
    m := func(ctx *fasthttp.RequestCtx) {
        switch string(ctx.Path()) {
        case "/test":
            test(ctx)
        default:
            fmt.Println(i)
            ctx.Error("not found", fasthttp.StatusNotFound)
        }
    }
    fasthttp.ListenAndServe(":80", m)
}

func test(ctx *fasthttp.RequestCtx) {
    i++
}

var i int = 0

output:

100000

2- With this Get:

package main

import (
    "fmt"
    "net/http"
    "time"
)

func main() {
    t := time.Now()
    for i := 0; i < 100000; i++ {
        read(`http://localhost/test`)
    }
    fmt.Println(time.Since(t))
    read(`http://localhost/`)
}

func read(url string) {
    _, err := http.Head(url)
    if err != nil {
        fmt.Println(err)
    }
}

output:

7.9454545s

3- Output of This code:

8.6294936s