简体   繁体   中英

Golang fasthttp very slow with request

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?

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

如果您使用的是 Windows,这个问题可能会给您一些线索

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM