value type vs reference type in

2020-01-08  本文已影响0人  老猫_2017

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()

上一篇下一篇

猜你喜欢

热点阅读