简体   繁体   中英

Why does my program run using so much memory?

I'm reading a book on Erlang and I make simple example from the book.

%% exrs.erl

-module(exrs).
-export([sum/1]).

sum(0) -> 0;
sum(N) -> N + sum(N - 1).

When I run this example for large number (ig 1000000000) it use 16Gb RAM and 48Gb swap file on my PC for calculation this function.

1> exrs:sum(1000000000).

Is this a usual behavior for Erlang VM? And how to avoid the problem like that?

PS:

10> erlang:system_info(version).
"11.1"
11> erlang:system_info(otp_release).
"23" 

OS: Win10 x64

As said in other answers, your recursion is not tail optimized. What happens in your code is that erlang evaluates right side of expression and recursively appends new function call to stack. Like below

1_000_000 + sum(999_999 + sum(999_998 + sum(....)))

That is what eats your memory. The proper way is to write function that accepts accumulator as second argument of sum function, like this

-module(exrs).
-export([sum/2]).

sum(0, ACC) -> ACC;
sum(N, ACC) -> sum(N - 1, ACC + N).

Your recursive function can't make use of tail-call optimisation, so it's using a stack frame for each recursive call.

1,000,000,000 recursive calls is a lot of stack frames.

See, for example, this section of "Learn you some Erlang", for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM