Golang fasthttp 为什么你这么优秀

最近,需要使用 http client 发送数据,网上都说

fasthttp 据说是目前golang性能最好的http库,相对于自带的net/http,性能说是有10倍的提升

参考:https://studygolang.com/articles/17716

让我们压力测试一下,看看结果如何

安装包

go get -u github.com/valyala/fasthttp

写个测试类  util_test.go

package test

import (
    "github.com/valyala/fasthttp"
    "net/http"
    "net/url"
    "strconv"
    "strings"
    "testing"
)

const serverUrl = "http://127.0.0.1:8080/server/v1/test"

// go 自带的net/http
func BenchmarkNetHttp(b *testing.B) {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        if err := netHttp(i); err != nil {
            b.Log(err)
        }
    }
    b.StopTimer()
}


// fasthttp
func BenchmarkFasthttp(b *testing.B) {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        if err := fastHttp(i); err != nil {
            b.Log(err)
        }
    }
    b.StopTimer()
}

func netHttp(i int) error{
    params := url.Values{}
    params.Add("content", strconv.Itoa(i))
    if resp, err := http.PostForm(serverUrl, params); err == nil && resp != nil {
        defer resp.Body.Close()
    } else {
        return err
    }
    return nil
}

// 代码参考:https://studygolang.com/articles/17716
func fastHttp(i int) error{
    req := fasthttp.AcquireRequest()
    defer fasthttp.ReleaseRequest(req) // 用完需要释放资源

    // 默认是application/x-www-form-urlencoded
    req.Header.SetContentType("application/json")
    req.Header.SetMethod("POST")

    req.SetRequestURI(serverUrl)

    // JSON 格式数据:`{"content":"1"}`
    requestBody := strings.Builder{}
    requestBody.WriteString(`{"content":`)
    requestBody.WriteString(strconv.Itoa(i))
    requestBody.WriteString("}")

    req.SetBody([]byte(requestBody.String()))

    resp := fasthttp.AcquireResponse()
    defer fasthttp.ReleaseResponse(resp) // 用完需要释放资源
    err := fasthttp.Do(req, resp)
    return err
}

进入到 util_test.go 所在的目录,执行命令

go test -bench=. -benchmem

-benchmem  可以查看内存分配的次数,知道为什么某些方法性能更优

测试结果: 

 

说明
被测试方法循环次数平均耗时平均使用内存大小平均内存分配次数
BenchmarkNetHttp-4   5000285588 ns/op14627 B/op 99 allocs/op
BenchmarkFasthttp-420000  94844 ns/op      37 B/op   2 allocs/op

总结:

fasthttp 主要是使用了“池化”的概念,它高性能主要源自于“复用”,占用更少的内存,更少内存的分配次数,节省了大量的资源分配成本。 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值