zoukankan      html  css  js  c++  java
  • 2.4 Buffer

    package main
    
    import (
    	"bytes"
    	"fmt"
    )
    
    func main() {
    	strings := []string{"This ", "is ", "even ",
    		"more ", "performant "}
    	buffer := bytes.Buffer{}
    	for _, val := range strings {
    		buffer.WriteString(val)
    	}
    
    	fmt.Println(buffer.String())
    }
    
    /*
    This is even more performant 
    
    */
    
    

    package main
    
    import (
    	"fmt"
    )
    
    func main() {
    
    	strings := []string{"This ", "is ", "even ",
    		"more ", "performant "}
    
    	bs := make([]byte, 100)
    	bl := 0
    
    	for _, val := range strings {
    		bl += copy(bs[bl:], []byte(val))
    	}
    
    	fmt.Println(string(bs[:]))
    
    }
    
    /*
    This is even more performant 
    
    */
    
    

    性能测试

    package bench
    
    import (
    	"bytes"
    	"testing"
    )
    
    const testString = "test"
    
    func BenchmarkConcat(b *testing.B) {
    	var str string
    	b.ResetTimer()
    	for n := 0; n < b.N; n++ {
    		str += testString
    	}
    	b.StopTimer()
    }
    
    func BenchmarkBuffer(b *testing.B) {
    	var buffer bytes.Buffer
    
    	b.ResetTimer()
    	for n := 0; n < b.N; n++ {
    		buffer.WriteString(testString)
    	}
    	b.StopTimer()
    }
    
    func BenchmarkCopy(b *testing.B) {
    	bs := make([]byte, b.N)
    	bl := 0
    
    	b.ResetTimer()
    	for n := 0; n < b.N; n++ {
    		bl += copy(bs[bl:], testString)
    	}
    	b.StopTimer()
    }
    
    
    

    go test -bench=.
    goos: darwin
    goarch: amd64
    pkg: go_web/bench
    BenchmarkConcat-8 500000 114962 ns/op
    BenchmarkBuffer-8 100000000 14.8 ns/op
    BenchmarkCopy-8 500000000 3.19 ns/op
    PASS
    ok go_web/bench 61.018s

  • 相关阅读:
    mssql锁
    gridview 分页兼容BOOTSTRAP
    BOOTSTRAP前端模板
    bootstrap 简单模板
    ajax 跨域访问的解决方案
    webapi之权限验证
    webapi权限常见错误
    ajax跨域解决方案
    iis 部署webapi常见错误及解决方案
    OOM AutoMapper的简单实用
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8620469.html
Copyright © 2011-2022 走看看