Erlang/OTP Forums

Author Message

<  Erlang  ~  Recursive function calls and stack

lucasm
Posted: Sun Apr 19, 2009 11:11 pm Reply with quote
Joined: 19 Apr 2009 Posts: 1
Hello.
When a function recursively calls itself, are all the parameters copied on to the stack? The reason I am asking: I recently wrote a program that was passing very long lists of integers (16000 +) to a function. The function would call itself recursively and pass along the very long list as a parameter. This particular implementation proved to be rather slow, and I am suspecting the culprit was that the very long list list was copied on the stack each time a function was called, resultint in a lot of memory traffic and usage. Is my understanding correct?

Thanks in advance, Lucas
View user's profile Send private message
uwiger
Posted: Mon Apr 20, 2009 1:33 pm Reply with quote
User Joined: 03 Jul 2006 Posts: 604 Location: Sweden
lucasm wrote:
Hello.
When a function recursively calls itself, are all the parameters copied on to the stack?


No. The list is created once and only referred to (with a pointer) on the stack. If the argument is passed along unchanged to the next function/iteration, the cost will be the same whether the argument is a huge list or a simple atom.

BR,
Ulf W
View user's profile Send private message Visit poster's website
seancribbs
Posted: Sun May 03, 2009 5:41 pm Reply with quote
User Joined: 03 May 2009 Posts: 17 Location: Chapel Hill, NC
lucasm wrote:
The reason I am asking: I recently wrote a program that was passing very long lists of integers (16000 +) to a function. The function would call itself recursively and pass along the very long list as a parameter. This particular implementation proved to be rather slow, and I am suspecting the culprit was that the very long list list was copied on the stack each time a function was called, resultint in a lot of memory traffic and usage.


This would only be the case if your recursive call is not the last thing in the function. Erlang is able to do TCO (tail-call optimization), which essentially amounts to a GOTO or JMP after the optimization. Try to refactor your function to call itself last. And what Ulf said.
View user's profile Send private message

Display posts from previous:  

All times are GMT
Page 1 of 1
This forum is locked: you cannot post, reply to, or edit topics.

Jump to:  

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum