为什么阶梯不会溢出Erlang的堆栈? [英] Why is factorial not overflowing the stack in Erlang?

查看:138
本文介绍了为什么阶梯不会溢出Erlang的堆栈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

-module(demo).
-export([factorial/1]).

factorial(0) -> 1;
factorial(N) -> 
    N * factorial(N-1).

阶乘不是尾递归的,但为什么它不会溢出堆栈?我可以在没有堆栈溢出的情况下得到10万的阶乘,但需要一些时间来计算。

The factorial is not tail recursive but why is it not overflowing the stack? I am able to get factorial of 100,000 without stack overflow but takes some time to compute.

推荐答案

一个Erlang进程的堆栈不存储在堆栈给系统给进程(通常是几兆字节)而是在堆中。据我所知,它将增长无限,直到系统拒绝给VM更多的记忆。

An Erlang process's "stack" is not stored in the stack given by the system to the process (which is usually a few megabytes) but in the heap. As far as I know, it will grow unbounded until the system refuses to give the VM more memory.


大小包含233个字堆区(,其中包含堆栈)。垃圾收集器根据需要增加堆。

The size includes 233 words for the heap area (which includes the stack). The garbage collector increases the heap as needed.

进程的主(外部)循环必须是尾递归的。否则,堆栈增长直到进程终止。

The main (outer) loop for a process must be tail-recursive. Otherwise, the stack grows until the process terminates.

如果您在OSX上的活动监视器或等进程监视器中监视Erlang VM进程,顶部在其他类UNIX系统上,您将看到内存使用量将持续增加,直到计算完成,此时内存的一部分(堆栈存储)将被释放(这个函数在函数返回给我几秒钟后逐渐发生)。

If you monitor the Erlang VM process in an process monitor like Activity Monitor on OSX or top on other UNIX-like systems, you'll see that the memory usage will keep on increasing until the calculation is complete, at which point a part of the memory (the one where the "stack" is stored) will be released (this happens gradually over a few seconds after the function returns for me).

这篇关于为什么阶梯不会溢出Erlang的堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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