zoukankan      html  css  js  c++  java
  • golang字符串拼接性能对比

    对比 +(运算符)、strings.Join、sprintf、bytes.Buffer对字符串拼接的性能

    package main
    
    import (
    	"bytes"
    	"fmt"
    	"strings"
    	"testing"
    )
    
    func TestfourPlusFour(t *testing.T) {
    	fmt.Println("testing")
    }
    
    func BenchmarkAddStringWithOperator(b *testing.B) {
    	hello := ""
    	for i := 0; i < b.N; i++ {
    		hello += "hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello"
    	}
    }
    
    func BenchmarkAddStringWithSptint(b *testing.B) {
    	hello := ""
    	for i := 0; i < b.N; i++ {
    		hello = fmt.Sprintf("%s%s", hello, "hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello")
    	}
    }
    
    func BenchmarkAddStringWithJoin(b *testing.B) {
    	hello := ""
    	for i := 0; i < b.N; i++ {
    		hello = strings.Join([]string{hello, "hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello"}, "")
    	}
    }
    
    func BenchmarkAddStringWithBuffer(b *testing.B) {
    	var buf bytes.Buffer
    	for i := 0; i < b.N; i++ {
    		buf.WriteString("hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello")
    	}
    	_ = buf.String()
    }
    

      运行测试结果:

    在一些性能要求较高的场合,尽量使用buf.WriteString()以获得较好的可读性

  • 相关阅读:
    zjoj1706: [usaco2007 Nov]relays 奶牛接力跑
    bzoj1784: [Usaco2010 Jan]island
    [PKUSC2018]真实排名
    [PKUSC2018]主斗地
    回来了
    P4887 第十四分块(前体)
    P3604 美好的每一天
    Codeforces Round #660(CF1388)
    BOI2020 DAY2
    BZOJ 5281--[Usaco2018 Open]Talent Show(分数规划&单调队列&DP)
  • 原文地址:https://www.cnblogs.com/wangjunqiao/p/11011012.html
Copyright © 2011-2022 走看看