关于Go切片截取的一个注意事项

go在使用切片截断时,底层数组没有改变,依然持有指向堆内存的指针,导致内存无法释放。

func split(arr []int) []int {
	newArr := arr[0:5]
	return newArr
}

以上切片newArr截取了切片arr中的部分数据并返回。如果切片arr在之后不再使用,即使切片newArr只使用了切片arr中的前5个数据而已,arr的整个底层数组都不会被GC回收。如果切片arr中含有大量的数据,一直不释放,那这会造成较大的浪费内存。

类似这种可以在截断前不需要的手动置空。

arr[5:] = nil
newArr := arr[0:5]

另外对于项目中Go代码情况可以pprof程序性能分析工具去查看。

This entry was posted in Go and tagged . Bookmark the permalink.

12 Responses

  1. Hey very cool website!! Man .. Excellent .. Amazing .. I’ll bookmark your web site and take the feeds also?KI’m glad to seek out a lot of useful information right here in the put up, we’d like work out more strategies on this regard, thanks for sharing. . . . . .

  2. I’ve been exploring for a bit for any high quality articles or blog posts in this kind of area . Exploring in Yahoo I eventually stumbled upon this website. Studying this info So i’m satisfied to express that I have a very just right uncanny feeling I discovered exactly what I needed. I such a lot indisputably will make certain to do not forget this website and provides it a glance on a constant basis.

  3. Thanks , I’ve recently been searching for information approximately this subject for a while and yours is the greatest I have found out so far. But, what in regards to the bottom line? Are you positive about the supply?

  4. Hello! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results. If you know of any please share. Thanks!

  5. I’m truly enjoying the design and layout of your website. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Fantastic work!

  6. Thanks for every other informative site. The place else may I am getting that kind of info written in such an ideal means? I have a mission that I am just now running on, and I’ve been on the glance out for such info.

graliontorile进行回复 取消回复

邮箱地址不会被公开。 必填项已用*标注