Swift 栈和堆理解 [英] Swift stack and heap understanding

查看:30
本文介绍了Swift 栈和堆理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想快速了解堆栈中存储的内容和堆中的内容.我有一个粗略的估计:您打印的所有内容和内存地址出现的不是值,它们存储在堆栈中,而作为值打印出来的东西,它们在堆上,基本上根据值和引用类型.我完全错了吗?或者,您能否提供堆栈/堆的可视化表示?

解决方案

分配在堆上的变量在运行时分配了它们的内存,访问这块内存会慢一点,但是堆大小只受虚拟内存大小的限制.堆的元素之间没有依赖关系,可以随时随机访问.您可以随时分配块并随时释放它.这使得在任何给定时间跟踪堆的哪些部分已分配或空闲变得更加复杂.

对于转义闭包:
要记住的一个重要注意事项是,如果存储在堆栈中的值在闭包中被捕获,该值将被复制到堆中,以便在执行闭包时它仍然可用.

更多参考:http://net-informations.com/faq/net/stack-heap.htm

I want to understand what is stored in the stack and heap in swift. I have a rough estimation: Everything that you print and the memory address appears not the values, those are stored in the stack, and what is printed out as values, those are on the heap, basically according to value and reference types. Am I completely wrong? And optionally, could you provide a visual representation of the stack/heap?

解决方案

As @Juul stated Reference types are stored in the Heap and values in the stack.

Here is the explanation:

Stack and Heap

Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM .

Variables allocated on the stack are stored directly to the memory, and access to this memory is very fast, and its allocation is determined when the program is compiled. When a function or a method calls another function which in turns calls another function, etc., the execution of all those functions remains suspended until the very last function returns its value. The stack is always reserved in a LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack. Freeing a block from the stack is nothing more than adjusting one pointer.

Variables allocated on the heap have their memory allocated at run time, and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory. Elements of the heap have no dependencies with each other and can always be accessed randomly at any time. You can allocate a block at any time and free it at any time. This makes it more complex to keep track of which parts of the heap are allocated or free at any given time.

For Escaping Closure:
An important note to keep in mind is that in cases where a value stored on a stack is captured in a closure, that value will be copied to the heap so that it's still available by the time the closure is executed.

For more reference: http://net-informations.com/faq/net/stack-heap.htm

这篇关于Swift 栈和堆理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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