在Go复制内存中进行切片分配 [英] Does slice assignment in Go copy memory

查看:68
本文介绍了在Go复制内存中进行切片分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目的:我有一个很大的缓冲区,并且我想要一个指向缓冲区中不同位置的指针数组/切片.

我在做什么:

  datPtrs:= make([] [] byte,n)对于我:= 0;我i ++ {datPtrs [i] = bigBuf [i * m:(i + 1)* m]} 

我的问题:

  1. 此副本存储器会吗?我的猜测不是,但是我找不到任何地方可以确认这一点.
  2. 找出是否存在内存副本的最佳方法/工具是什么?

解决方案

Go slice被实现为结构:

src/runtime/slice.go :

  type slice struct {数组不安全len intcap int} 

您正在分配/复制切片结构,该结构不复制基础数组,而仅复制其指针.


一个简单的例子:

 程序包主要进口 ("fmt")func main(){buf:= make([] byte,8)对于我:=范围buf {buf [i] =字节(i)}子:= buf [1:3]fmt.Println(buf)fmt.Println(子)对于我:=范围子{子[i] + = 43}fmt.Println(buf)fmt.Println(子)} 

游乐场: https://play.golang.org/p/4OzPwuNmUlY

输出:

  [0 1 2 3 4 5 6 7][1 2][0 44 45 3 4 5 6 7][44 45] 


请参见 The Go博客:Go Slices:用法和内部原理

Purpose: I have a big buffer, and I would like to have an array/slice of pointer pointing to different loc in the buffer.

What I am doing:

datPtrs := make([][]byte, n)
for i:=0; i<n; i++{
    datPtrs[i] = bigBuf[i*m:(i+1)*m]
}

My Question:

  1. Will this copy memory? My guess is not, but I cannot find anywhere to confirm this.
  2. What is the best way/tool to find out whether there is memory copy or not?

解决方案

Go slices are implemented as a struct:

src/runtime/slice.go:

type slice struct {
    array unsafe.Pointer
    len   int
    cap   int
}

You are assigning/copying the slice struct, which does not copy the underlying array, only its pointer.


A simple illustration:

package main

import (
    "fmt"
)

func main() {
    buf := make([]byte, 8)
    for i := range buf {
        buf[i] = byte(i)
    }
    sub := buf[1:3]
    fmt.Println(buf)
    fmt.Println(sub)
    for i := range sub {
        sub[i] += 43
    }
    fmt.Println(buf)
    fmt.Println(sub)
}

Playground: https://play.golang.org/p/4OzPwuNmUlY

Output:

[0 1 2 3 4 5 6 7]
[1 2]
[0 44 45 3 4 5 6 7]
[44 45]


See The Go Blog: Go Slices: usage and internals,

这篇关于在Go复制内存中进行切片分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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