Go没有真正的方法来缩小切片吗?这是一个问题吗? [英] Does Go have no real way to shrink a slice? Is that an issue?

查看:95
本文介绍了Go没有真正的方法来缩小切片吗?这是一个问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试去一段时间,这个问题一直在困扰着我。假设我在一片中建立了一个有点大的数据集(比如说,一千万个int64)。

 包主
$ b导入(
数学
fmt


func main(){
var a [] int64
var i int64;
upto:= int64(math.Pow10(7))
for i = 0;我<取决于; i ++ {
a = append(a,i)
}
fmt.Println(cap(a))
}

但是我决定我不想要其中的大部分,所以我想最终只分了一部分。我已经在Go的wiki上尝试了切片和删除技巧,但它们都没有减少切片的容量。



这就是我的问题:Go没有真正缩小与 realloc()类似的切片容量的方法。 -ing与之前调用C中的同一个指针时的较小大小参数相比较?这是一个问题,应该怎么处理呢?

解决方案

执行切片的重新分配:

  a = append([] T(nil),a [:newSize] ...)//感谢@Dijkstra指出缺失的省略号。 

如果它复制了 newSize 元素到一个新的内存位置,或者如果它确实有一个实际的 调整大小,就像realloc(3)一样,完全由编译器自行决定。您可能需要调查当前状态,并且如果有房间,则可能会提出问题在这方面有所改进。

然而,这可能是一个微观优化。性能增强的第一个来源几乎总是在选择更好的算法和/或更好的数据结构。编辑:上面只是部分正确的。编辑:上面只是部分正确的。编辑:上面只是部分正确的。在通常情况下,编译器不能派生,如果有其他指针指向切片的后备数组。因此realloc不适用。上面的代码片段实际上是保证的来形成'newSize'元素的副本。对不起,可能会产生任何混淆。


I've been trying out Go for some time and this question keeps bugging me. Say I build up a somewhat large dataset in a slice (say, 10 million int64s).

package main

import (
    "math"
    "fmt"
)

func main() {
    var a []int64
    var i int64;
    upto := int64(math.Pow10(7))
    for i = 0; i < upto; i++ {
        a = append(a, i)
    }
    fmt.Println(cap(a))
}

But then I decide I don't want most of them so I want to end up with a slice of just 10 of those. I've tried both slicing and delete techniques on Go's wiki but none of them seem to reduce the slice's capacity.

So that's my question: does Go has no real way of shrinking the capacity of a slice that would be similar to realloc()-ing with a smaller size argument than in your previous call on the same pointer in C? Is that an issue and how should one deal with it?

解决方案

To perform an, in effect, a realloc of a slice:

a = append([]T(nil), a[:newSize]...) // Thanks to @Dijkstra for pointing out the missing ellipsis.

If it does a copy of newSize elements to a new memory place or if it does an actual in place resize as in realloc(3) is at complete discretion of the compiler. You might want to investigate the current state and perhaps raise an issue if there's a room for improvement in this.

However, this is likely a micro-optimization. The first source of performance enhancements lies almost always in selecting a better algorithm and/or a better data structure. Using a hugely sized vector to finally keep a few items only is probably not the best option wrt to memory consumption.

EDIT: The above is only partially correct. The compiler cannot, in the general case, derive if there are other pointers to the slice's backing array. Thus the realloc is not applicable. The above snippet is actually guaranteed to peform a copy of 'newSize' elements. Sorry for any confusion possibly created.

这篇关于Go没有真正的方法来缩小切片吗?这是一个问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆