您的位置 首页 golang

Golang String使用的内存分配优化

请看如下2个方法思考那个更快为什么?

 package main

import "strings"

func Test() string{
var s string
for i:=1;i<1000;i++{
s+= "a"
}
return s
}


func Test2() string{
s := make([]string,1000)
for i:=1;i<1000;i++{
s[i]= "a"
}
return strings.Join(s,"")
}

  

压测结果如下

 package main

import "testing"

func BenchmarkTest(b *testing.B){
   for i:=0;i<b.N;i++{
      Test()
   }
}

func BenchmarkTest2(b *testing.B){
   for i:=0;i<b.N;i++{
      Test2()
   }
}
  

go test -bench=. -benchmem -run=none

goos: darwin

goarch: amd64

pkg: goRpa

cpu: Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz

BenchmarkTest-12 8737 137087 ns/op 529248 B/op 998 allocs/op

BenchmarkTest2-12 118814 9031 ns/op 1024 B/op 1 allocs/op

PASS

ok goRpa 3.620s

原因是在test()方法中 string每次 s+=”a”的时候都会重新分配内存

string底层结构

typ stringStruct struct {

str unsafe.Pointer

len int

}

在使用string前最好提前定义好字符串长度

文章来源:智云一二三科技

文章标题:Golang String使用的内存分配优化

文章地址:https://www.zhihuclub.com/97201.shtml

关于作者: 智云科技

热门文章

网站地图