美文网首页
value type vs reference type in

value type vs reference type in

作者: 老猫_2017 | 来源:发表于2020-01-08 16:13 被阅读0次

    swift 中 值类型 vs 引用类型

    整理如下:

    类型 存储 备注 比喻
    Value Type 值类型 Get Stored on Stack Memory 栈 在栈上 cpu管理内存分配,回收 不同的对象地址,互不影响
    Reference Type 引用类型 Get Stored on Managed Heap Memory堆 在堆上,用户管理内存分配处理,有引用计数规则 皮影戏,任何一个操作,都会跟着动,指向同一个对象,相互影响

    value type 在栈上的,最大的优势是 编译器自动管理内存,速度快,更适合与多线程开发, 内存大小是有限制的,大小有编译器决定,采用FILO的数据结构

    reference type 引用类型,共享对象时使用,在堆上,用户自己管理内存。 内存大小比栈要大的多

    swift 类型 内存分配区域 备注
    struct stack Value Type
    Enumerations stack Value Type
    tuples stack Value Type
    set stack Value Type
    array stack Value Type
    dictionary stack Value Type
    Int stack Value Type
    String stack Value Type
    Double stack Value Type
    Bool stack Value Type
    class heap Reference Type, class 中的属性 struct 等都在 heap 上
    Functions heap Reference Type
    Closures heap Reference Type
    存储类型结构图

    Stack
    very fast access
    don't have to explicitly de-allocate variables
    space is managed efficiently by CPU, memory will not become fragmented
    local variables only
    limit on stack size (OS-dependent)
    variables cannot be resized

    Heap
    variables can be accessed globally
    no limit on memory size
    (relatively) slower access
    no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed
    you must manage memory (you're in charge of allocating and freeing variables)
    variables can be resized using realloc()

    相关文章

      网友评论

          本文标题:value type vs reference type in

          本文链接:https://www.haomeiwen.com/subject/zjssactx.html