golang数组内存分配原理

目录
  • 编译时数组类型解析
    • ArrayType
    • types2.Array
    • types.Array
  • 编译时数组字面量初始化
  • 编译时数组索引越界检查
  • 运行时数组内存分配
  • 总结

编译时数组类型解析

ArrayType

数组是内存中一片连续的区域,在声明时需要指定长度,数组的声明有如下三种方式,[...]的方式在编译时会自动推断长度。

var arr1 [3]int
var arr2 = [3]int{1,2,3}
arr3 := [...]int{1,2,3}

在词法及语法解析时,上述三种方式声明的数组会被解析为ArrayType, 当遇到[...]的声明时,其长度会被标记为nil,将在后续阶段进行自动推断。

// go/src/cmd/compile/internal/syntax/parser.go
func (p *parser) typeOrNil() Expr {
  ...
    pos := p.pos()
    switch p.tok {
    ...
    case _Lbrack:
        // '[' oexpr ']' ntype
        // '[' _DotDotDot ']' ntype
        p.next()
        if p.got(_Rbrack) {
            return p.sliceType(pos)
        }
        return p.arrayType(pos, nil)
  ...
}
// "[" has already been consumed, and pos is its position.
// If len != nil it is the already consumed array length.
func (p *parser) arrayType(pos Pos, len Expr) Expr {
    ...
    if len == nil && !p.got(_DotDotDot) {
        p.xnest++
        len = p.expr()
        p.xnest--
    }
    ...
    p.want(_Rbrack)
    t := new(ArrayType)
    t.pos = pos
    t.Len = len
    t.Elem = p.type_()
    return t
}
// go/src/cmd/compile/internal/syntax/nodes.go
type (
  ...
    // [Len]Elem
    ArrayType struct {
        Len  Expr // nil means Len is ...
        Elem Expr
        expr
    }
  ...
)

types2.Array

在对生成的表达式进行类型检查时,如果是ArrayType类型,且其长度Lennil时,会初始化一个types2.Array并将其长度标记为-1,然后通过check.indexedElts(e.ElemList, utyp.elem, utyp.len)返回数组长度n并赋值给Len,完成自动推断。

// go/src/cmd/compile/internal/types2/array.go
// An Array represents an array type.
type Array struct {
    len  int64
    elem Type
}
// go/src/cmd/compile/internal/types2/expr.go
// exprInternal contains the core of type checking of expressions.
// Must only be called by rawExpr.
func (check *Checker) exprInternal(x *operand, e syntax.Expr, hint Type) exprKind {
    ...
    switch e := e.(type) {
    ...
    case *syntax.CompositeLit:
        var typ, base Type

        switch {
        case e.Type != nil:
            // composite literal type present - use it
            // [...]T array types may only appear with composite literals.
            // Check for them here so we don't have to handle ... in general.
            if atyp, _ := e.Type.(*syntax.ArrayType); atyp != nil && atyp.Len == nil {
                // We have an "open" [...]T array type.
                // Create a new ArrayType with unknown length (-1)
                // and finish setting it up after analyzing the literal.
                typ = &Array{len: -1, elem: check.varType(atyp.Elem)}
                base = typ
                break
            }
            typ = check.typ(e.Type)
            base = typ
      ...
        }

        switch utyp := coreType(base).(type) {
        ...
        case *Array:
            if utyp.elem == nil {
                check.error(e, "illegal cycle in type declaration")
                goto Error
            }
            n := check.indexedElts(e.ElemList, utyp.elem, utyp.len)
            // If we have an array of unknown length (usually [...]T arrays, but also
            // arrays [n]T where n is invalid) set the length now that we know it and
            // record the type for the array (usually done by check.typ which is not
            // called for [...]T). We handle [...]T arrays and arrays with invalid
            // length the same here because it makes sense to "guess" the length for
            // the latter if we have a composite literal; e.g. for [n]int{1, 2, 3}
            // where n is invalid for some reason, it seems fair to assume it should
            // be 3 (see also Checked.arrayLength and issue #27346).
            if utyp.len < 0 {
                utyp.len = n
                // e.Type is missing if we have a composite literal element
                // that is itself a composite literal with omitted type. In
                // that case there is nothing to record (there is no type in
                // the source at that point).
                if e.Type != nil {
                    check.recordTypeAndValue(e.Type, typexpr, utyp, nil)
                }
            }
        ...
        }
    ...
}

types.Array

在生成中间结果时,types2.Array最终会通过types.NewArray()转换成types.Array类型。

// go/src/cmd/compile/internal/noder/types.go
// typ0 converts a types2.Type to a types.Type, but doesn't do the caching check
// at the top level.
func (g *irgen) typ0(typ types2.Type) *types.Type {
    switch typ := typ.(type) {
    ...
    case *types2.Array:
        return types.NewArray(g.typ1(typ.Elem()), typ.Len())
    ...
}
// go/src/cmd/compile/internal/types/type.go
// Array contains Type fields specific to array types.
type Array struct {
    Elem  *Type // element type
    Bound int64 // number of elements; <0 if unknown yet
}
// NewArray returns a new fixed-length array Type.
func NewArray(elem *Type, bound int64) *Type {
    if bound < 0 {
        base.Fatalf("NewArray: invalid bound %v", bound)
    }
    t := newType(TARRAY)
    t.extra = &Array{Elem: elem, Bound: bound}
    t.SetNotInHeap(elem.NotInHeap())
    if elem.HasTParam() {
        t.SetHasTParam(true)
    }
    if elem.HasShape() {
        t.SetHasShape(true)
    }
    return t
}

编译时数组字面量初始化

数组类型解析可以得到数组元素的类型Elem以及数组长度Bound,而数组字面量的初始化是在编译时类型检查阶段完成的,通过函数tcComplit -> typecheckarraylit循环字面量分别进行赋值。

// go/src/cmd/compile/internal/typecheck/expr.go
func tcCompLit(n *ir.CompLitExpr) (res ir.Node) {
    ...
    t := n.Type()
    base.AssertfAt(t != nil, n.Pos(), "missing type in composite literal")

    switch t.Kind() {
    ...
    case types.TARRAY:
        typecheckarraylit(t.Elem(), t.NumElem(), n.List, "array literal")
        n.SetOp(ir.OARRAYLIT)
    ...

    return n
}
// go/src/cmd/compile/internal/typecheck/typecheck.go
// typecheckarraylit type-checks a sequence of slice/array literal elements.
func typecheckarraylit(elemType *types.Type, bound int64, elts []ir.Node, ctx string) int64 {
    ...
    for i, elt := range elts {
        ir.SetPos(elt)
        r := elts[i]
        ...
        r = Expr(r)
        r = AssignConv(r, elemType, ctx)
        ...
}

编译时数组索引越界检查

在对数组进行索引访问时,如果访问越界在编译时就无法通过检查。

例如:

arr := [...]string{"s1", "s2", "s3"}
e3 := arr[3]
// invalid array index 3 (out of bounds for 3-element array)

数组在类型检查阶段会对访问数组的索引进行验证:

// go/src/cmd/compile/internal/typecheck/typecheck.go
func typecheck1(n ir.Node, top int) ir.Node {
  ...
    switch n.Op() {
  ...
  case ir.OINDEX:
        n := n.(*ir.IndexExpr)
        return tcIndex(n)
  ...
  }
}
// go/src/cmd/compile/internal/typecheck/expr.go
func tcIndex(n *ir.IndexExpr) ir.Node {
    ...
    l := n.X
    n.Index = Expr(n.Index)
    r := n.Index
    t := l.Type()
    ...
    switch t.Kind() {
    ...
    case types.TSTRING, types.TARRAY, types.TSLICE:
        n.Index = indexlit(n.Index)
        if t.IsString() {
            n.SetType(types.ByteType)
        } else {
            n.SetType(t.Elem())
        }
        why := "string"
        if t.IsArray() {
            why = "array"
        } else if t.IsSlice() {
            why = "slice"
        }
        if n.Index.Type() != nil && !n.Index.Type().IsInteger() {
            base.Errorf("non-integer %s index %v", why, n.Index)
            return n
        }
        if !n.Bounded() && ir.IsConst(n.Index, constant.Int) {
            x := n.Index.Val()
            if constant.Sign(x) < 0 {
                base.Errorf("invalid %s index %v (index must be non-negative)", why, n.Index)
            } else if t.IsArray() && constant.Compare(x, token.GEQ, constant.MakeInt64(t.NumElem())) {
                base.Errorf("invalid array index %v (out of bounds for %d-element array)", n.Index, t.NumElem())
            } else if ir.IsConst(n.X, constant.String) && constant.Compare(x, token.GEQ, constant.MakeInt64(int64(len(ir.StringVal(n.X))))) {
                base.Errorf("invalid string index %v (out of bounds for %d-byte string)", n.Index, len(ir.StringVal(n.X)))
            } else if ir.ConstOverflow(x, types.Types[types.TINT]) {
                base.Errorf("invalid %s index %v (index too large)", why, n.Index)
            }
        }
    ...
    }
    return n
}

运行时数组内存分配

数组是内存区域一块连续的存储空间。在运行时会通过mallocgc给数组分配具体的存储空间。newarray中如果数组元素刚好只有一个,则空间大小为元素类型的大小typ.size, 如果有多个元素则内存大小为n*typ.size。但这并不是实际分配的内存大小,实际分配多少内存,取决于mallocgc,涉及到golang的内存分配原理。但可以看到如果待分配的对象不超过32kb,mallocgc会直接将其分配在缓存空间中,如果大于32kb则直接从堆区分配内存空间。

// go/src/runtime/malloc.go
// newarray allocates an array of n elements of type typ.
func newarray(typ *_type, n int) unsafe.Pointer {
    if n == 1 {
        return mallocgc(typ.size, typ, true)
    }
    mem, overflow := math.MulUintptr(typ.size, uintptr(n))
    if overflow || mem > maxAlloc || n < 0 {
        panic(plainError("runtime: allocation size out of range"))
    }
    return mallocgc(mem, typ, true)
}
// Allocate an object of size bytes.
// Small objects are allocated from the per-P cache's free lists.
// Large objects (> 32 kB) are allocated straight from the heap.
func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
    ...
}

总结

数组在编译阶段最终被解析为types.Array类型,包含元素类型Elem和数组长度Bound

type Array struct {
  Elem  *Type // element type
  Bound int64 // number of elements; <0 if unknown yet
}
  • 如果数组长度未指定,例如使用了语法糖[...],则会在表达式类型检查时计算出数组长度。
  • 数组字面量初始化以及索引越界检查都是在编译时类型检查阶段完成的。
  • 在运行时通过newarray()函数对数组内存进行分配,如果数组大小超过32kb则会直接分配到堆区内存。

到此这篇关于golang数组内存分配原理的文章就介绍到这了,更多相关golang数组原理内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • golang数组和切片作为参数和返回值的实现

    目录 1. 数组作为参数和返回值时 1.1数组的定义 1.2数组作为参数和返回值的时候 2.切片作为参数和返回值 2.1 切片的定义初始化 2.2 切片的存储大致分为3部分 2.3 切片作为参数和返回值 2.4 append 切片动态增长的原理 2.5 copy 函数 通过赋值切片可以使得两个切片的数据不共享 3. 总结: 1. 数组作为参数和返回值时 1.1数组的定义 数组是具有相同唯一类型的一组已编号且长度固定的数据项序列,这种类型可以是任意的原始类型例如整型.字符串或者自定义类型 var

  • golang实现PHP数组特性的方法

    目录 前言 内容 1. php 处理复杂结构 2. golang 处理复杂结构 3. dataBox 复杂结构处理 总结 前言 我们做业务过程中,对应强类型语言使用有个痛点,就是使用变量之前一定要定义变量类型,比如c,c++,golang等,弱类型语言择不需要,可以直接读写,比如php.下面通过php和golang语言举例说明,对于强弱类型语言变量类型的使用情况,并提出自己的解决方案databox. 内容 复杂结构处理 1. php 处理复杂结构 1.1 读取值 <?php $country =

  • Golang二维数组的使用方式

    ★二维数组的使用方式: 先声明或者定义,再赋值 1)语法:var 数组名[大小][大小]类型 2)比如:var arr[2][3]int[][] 两行三列的二维数组 ★二维数组的遍历 1)双层for循环 2)for-range方式完成遍历 package main import ( "fmt" ) func main() { //演示二维数组的遍历 var arr3 = [2][3]int{{1,2,3},{4,5,6}} //for循环来遍历 for i :=0;i < len

  • golang实现数组分割的示例代码

    需求:给定一个数组和一个正整数,要求把数组分割成多个正整数大小的数组,如果不够分,则最后一个数组分到剩余的所有元素. 示例1: 数组:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],正整数:2 期望结果: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] 示例2: 数组:[1, 2, 3, 4, 5, 6, 7, 8, 9],正整数:2 期望结果: [[1, 2], [3, 4], [5, 6], [7, 8], [9]] 下面是我的实现代码:

  • Golang中interface{}转为数组的操作

    interface{} 转为普通类型 我们都知道在golang中interface{}可以代表任何类型,对于像int64.bool.string等这些简单类型,interface{}类型转为这些简单类型时,直接使用 p, ok := t.(bool) p, ok := t.(int64) 如果ok==true的话,就已经类型转换成功. 假设有这样一个场景,我们有一个函数有返回值,但是返回值的类型不定,所以我们的返回值类型只能以接口来代替了. 返回接口类型之后,我们就要对其类型进行判断然后进行类型

  • golang 数组去重,利用map的实现

    目录 golang数组去重利用map golang删除排序数组中的重复项 golang数组去重利用map 可以利用go中,map数据类型的key唯一的属性,来对数组去重 将strSlice数组中重复的元素去掉,使其中的元素唯一 var strMap make(map[string]string) strSlice := []string {"slice","int","string","int","boolean&q

  • Golang 字符串与字节数组互转的实现

    目录 一.字符串与字节数组? 二.详细代码 1.字节转字符串 2.字符串转字节数组 3.完整运行测试 总结 一.字符串与字节数组? 字符串是 Go 语言中最常用的基础数据类型之一,本质上是只读的字符型数组,虽然字符串往往都被看做是一个整体,但是实际上字符串是一片连续的内存空间. Go 语言中另外一个类型字节(Byte).在ASCII中,一个英文字母占一个字节的空间,一个中文汉字占两个字节的空间.英文标点占一个字节,中文标点占两个字节.一个Byte数组中的元素对应一个ASCII码. 二.详细代码

  • golang数组内存分配原理

    目录 编译时数组类型解析 ArrayType types2.Array types.Array 编译时数组字面量初始化 编译时数组索引越界检查 运行时数组内存分配 总结 编译时数组类型解析 ArrayType 数组是内存中一片连续的区域,在声明时需要指定长度,数组的声明有如下三种方式,[...]的方式在编译时会自动推断长度. var arr1 [3]int var arr2 = [3]int{1,2,3} arr3 := [...]int{1,2,3} 在词法及语法解析时,上述三种方式声明的数组

  • javascript内存分配原理实例分析

    本文实例讲述了javascript内存分配原理.分享给大家供大家参考,具体如下: JavaScript中的变量分为两种,原始值和引用值.原始值指的是原始数据类型的值,比如undefined,null,number,string,boolean类型所表示的值.引用值指的是复合数据类型的值,即Object,Function,Array等. 原始值和引用值存储在内存中的位置分别为栈和堆.原始值是存储在栈中的简单数据段,他们的值直接存储在变量访问的位置.引用值是存储在堆中的对象. 存储在栈中的值是一个指

  • 基于Java 数组内存分配的相关问题

    可能Java 数组大家都很熟悉,最近我遇到了一个关于Java 数组内存分配的问题.呵呵.突然就发现许多书上"基本数据类型存储在栈内存当中,对象则保存在堆内存"这句话完全是错误的.下面是个简单的例子代码: 复制代码 代码如下: public class Test {    public static void main(String[] argv) {// 静态初始化数组String[] names = { "Michael", "Orson",

  • JVM对象创建和内存分配原理解析

    创建对象 当 JVM 收到一个 new 指令时,会检查指令中的参数在常量池是否有这个符号的引用,还会检查该类是否已经被加载过了,如果没有的话则要进行一次类加载. 接着就是分配内存了,通常有两种方式: 指针碰撞 空闲列表 使用指针碰撞的前提是堆内存是完全工整的,用过的内存和没用的内存各在一边每次分配的时候只需要将指针向空闲内存一方移动一段和内存大小相等区域即可. 当堆中已经使用的内存和未使用的内存互相交错时,指针碰撞的方式就行不通了,这时就需要采用空闲列表的方式.虚拟机会维护一个空闲的列表,用于记

  • 理解Javascript_01_理解内存分配原理分析

    原始值和引用值 在ECMAScript中,变量可以存放两种类型的值,即原始值和引用值. 原始值指的就是代表原始数据类型(基本数据类型)的值,即Undefined,Null,Number,String,Boolean类型所表示的值. 引用值指的就是复合数据类型的值,即Object,Function,Array,以及自定义对象,等等 栈和堆 与原始值与引用值对应存在两种结构的内存即栈和堆 栈是一种后进先出的数据结构,在javascript中可以通过Array来模拟栈的行为 复制代码 代码如下: va

  • Java 内存分配深入理解

    Java 内存分配深入理解 本文将由浅入深详细介绍Java内存分配的原理,以帮助新手更轻松的学习Java.这类文章网上有很多,但大多比较零碎.本文从认知过程角度出发,将带给读者一个系统的介绍. 进入正题前首先要知道的是Java程序运行在JVM(Java  Virtual Machine,Java虚拟机)上,可以把JVM理解成Java程序和操作系统之间的桥梁,JVM实现了Java的平台无关性,由此可见JVM的重要性.所以在学习Java内存分配原理的时候一定要牢记这一切都是在JVM中进行的,JVM是

  • C语言中多维数组的内存分配和释放(malloc与free)的方法

    如果要给二维数组(m*n)分配空间,代码可以写成下面: 复制代码 代码如下: char **a, i; // 先分配m个指针单元,注意是指针单元 // 所以每个单元的大小是sizeof(char *) a = (char **) malloc(m * sizeof(char * )); // 再分配n个字符单元, // 上面的m个指针单元指向这n个字符单元首地址 for(i = 0; i < m; i++) a[i] = (char * )malloc(n * sizeof(char )); 释

  • 浅谈C++内存分配及变长数组的动态分配

    第一部分 C++内存分配 一.关于内存 1.内存分配方式 内存分配方式有三种: (1)从静态存储区域分配.内存在程序编译的时候就已经分配好,这块内存在程序的整个运行期间都存在 例如全局变量,static变量. (2)在栈上创建.在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时这些存 储单元自动被释放.栈内存分配运算内置于处理器的指令集中,效率很高,但是分配的内存容量有限. (3) 从堆上分配,亦称动态内存分配.程序在运行的时候用malloc或new申请任意多少的内存,程序员

  • PHP数组实际占用内存大小原理解析

    一般来说,PHP数组的内存利用率只有 1/10, 也就是说,一个在C语言里面100M 内存的数组,在PHP里面就要1G.下面我们可以粗略的估算PHP数组占用内存的大小,首先我们测试1000个元素的整数占用的内存: <?php echo memory_get_usage() , '<br>'; $start = memory_get_usage(); $a = Array(); for ($i=0; $i<1000; $i++) { $a[$i] = $i + $i; } $mid

  • C++使用new和delete进行动态内存分配与数组封装

    目录 1.使用new申请内存 2.使用delete释放内存 3.使用new申请内存时的初始值 4.使用new和delete申请和释放数组空间 5.用类封装new申请和释放的数组空间 6.使用new申请多维数组 1.使用new申请内存 在某些情况下,程序只有在运行期间才能确定所需内存大小,此时应该使用new申请内存.申请成功的情况下会返回首地址,通过指向首地址的指针可以访问申请的内存,使用new申请内存的的语法如下: new 数据类型(初始化参数列表); 下面的例子定义了Duck类型的指针,并通过

随机推荐