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

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

问题描述

我想了解堆栈中存储的内容以及迅速存储的内容.我有一个粗略的估计: 基本上,您打印的所有内容和内存地址都不是值,而是存储在堆栈中的内容,以及作为值打印出来的内容,这些内容都在堆中,基本上根据值和引用类型而定.我完全错了吗?并且可以选择以可视方式表示堆栈/堆吗?

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?

推荐答案

@Juul 所述,引用类型存储在堆中的堆和值.

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

以下是说明:

堆栈和堆

堆栈用于静态内存分配,而堆用于动态内存分配,两者均存储在计算机的RAM中.

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

在堆栈上分配的变量直接存储到内存,并且对该内存的访问非常快,并且在程序编译时就确定了其分配.当一个函数或方法调用另一个函数,然后依次调用另一个函数等时,所有这些函数的执行将保持挂起状态,直到最后一个函数返回其值为止.堆栈始终按LIFO顺序保留,最近保留的块始终是要释放的下一个块.这使得跟踪堆栈真的非常简单.从堆栈中释放一个块无非就是调整一个指针.

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.

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

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

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