dtueufe82643 2019-03-02 08:25
浏览 12
已采纳

附加到长度未知的大数组的最佳执行方式

There are several ways how to append to an array. Wondering is there known best performing way for appending to a huge array (100Mb) with unknown length? I want to avoid copying as it is increases chances to run out of memory and it will degrade performance. Should I consider using two dimensional arrays?

  • 写回答

2条回答 默认 最新

  • douba6365 2019-03-02 09:39
    关注

    In Golang we have array and slice.


    Arrays have fixed size, when you need more space you need to create bigger array copy all values from the old array and replace the old reference with the new array.

    You should not hold the reference to the old array, so this memory will be garbage collected.


    Alternatively, you can use slices (which is a wrapper on top of an array). Resize and copy will be done for you automatically.
    You can also control resize manually, this could reduce GC. But it should be profiled and compared with slices.

    I've added an example with storing in a multi-dimension array, I strongly recommend avoiding this approach. It will make traversal more complex and slower, high probability of memory leaks and many more. GC in Golang is extreamly fast.

    BenchmarkStore/array-6            100000         20090 ns/op           0 B/op          0 allocs/op
    BenchmarkStore/slice-6              5000        259940 ns/op     4654337 B/op         30 allocs/op
    BenchmarkStore/Custom-6            10000        194152 ns/op     1747860 B/op          8 allocs/op
    BenchmarkStore/Dimensions-6         3000        418654 ns/op     4458593 B/op         20 allocs/op
    
    package main
    
    import (
        "testing"
    )
    
    const size = 100000
    
    // Wrapper around slice
    type MyStore struct {
        growthFactor int
        watermark    int
        Data         []int
    }
    
    func NewMyStore(growthFactor, initialSize int) *MyStore {
        return &MyStore{growthFactor: growthFactor, watermark: -1, Data: make([]int, initialSize)}
    }
    
    func (s *MyStore) Append(v int) {
        nextPosition := s.watermark + 1
        currentSize := len(s.Data)
        full := currentSize == nextPosition
        if full {
            dataResize := make([]int, currentSize*s.growthFactor)
            copy(dataResize, s.Data)
            s.Data = dataResize
        }
    
        s.Data[nextPosition] = v
        s.watermark = nextPosition
    }
    
    // Dimensions
    const chunkSize = 10
    type MyStoreMultiDimensions struct {
        size      int
        watermark int
        data      [][chunkSize]int
    }
    
    func NewStoreMultiDimensions(chunks int) *MyStoreMultiDimensions {
        return &MyStoreMultiDimensions{watermark: -1, data: make([][chunkSize]int, chunks)}
    }
    
    func (s *MyStoreMultiDimensions) Append(v int) {
        nextPosition := s.watermark + 1
        chunk := nextPosition / chunkSize
        if len(s.data) <= chunk {
            s.data = append(s.data, [chunkSize]int{})
        }
    
        s.data[chunk][nextPosition%chunkSize] = v
        s.watermark = nextPosition
    }
    
    func BenchmarkStore(b *testing.B) {
        b.Run("array", func(b2 *testing.B) {
            for i := 0; i < b2.N; i++ {
                var store [size]int
                for item := 0; item < size; item++ {
                    store[item] = item
                }
            }
        })
        b.Run("slice", func(b2 *testing.B) {
            for i := 0; i < b2.N; i++ {
                var store []int
                for item := 0; item < size; item++ {
                    store = append(store, item)
                }
            }
        })
        b.Run("Custom", func(b2 *testing.B) {
            for i := 0; i < b2.N; i++ {
                var store = NewMyStore(4, 10)
                for item := 0; item < size; item++ {
                    store.Append(item)
                }
            }
        })
        b.Run("Dimensions", func(b2 *testing.B) {
            for i := 0; i < b2.N; i++ {
                var store = NewStoreMultiDimensions(2)
                for item := 0; item < size; item++ {
                    store.Append(item)
                }
            }
        })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的