1

I have a ruby service that keeps running forever and I wonder whats the cost of recursivity. When I ctrl-c the service after some time, I get the following error printed:

^Cff.rb:169:in `sleep': Interrupt
    from ff.rb:169:in `fetch'
    from ff.rb:170:in `fetch'
    from ff.rb:187:in `fetch'
    from ff.rb:180:in `fetch'
    from ff.rb:170:in `fetch'
    from ff.rb:187:in `fetch'
    from ff.rb:177:in `fetch'
    from ff.rb:170:in `fetch'
 .... and continue for each recursive call

This makes me wonder if this has a memory cost or if it eventually will fail? Is it bad to use recursive in Ruby like this? Would another solution be better? Ty.

grm
  • 5,197
  • 5
  • 29
  • 35
  • 3
    I don't think that "recursivity" is a word. – Jacob Relkin Sep 24 '11 at 13:07
  • Looks like you need a loop instead of a recursive call. Recursion is not intended to run deeper forever, and it doesn't matter if it is Ruby, C or whatever. – sidyll Sep 24 '11 at 13:08
  • 1
    @JacobRelkin It's on [wiktionary](http://en.wiktionary.org/wiki/recursivity) so it must be true ;) – Dave Newton Sep 24 '11 at 13:08
  • 2
    @grm Sure, there's a memory cost--the stack keeps growing. That doesn't make recursion fundamentally bad, though--it's only bad it there's no "stop it!" condition. Doesn't mean you should be using recursion in *this* situation, though; we don't know. – Dave Newton Sep 24 '11 at 13:11
  • You've heard of the expression "select is not broken", right? – Andrew Grimm Sep 24 '11 at 14:13
  • For some reason I assumed it had no cost in ruby and was surprised. Thanks for your help! – grm Sep 24 '11 at 16:10

1 Answers1

1

AFIAK, Ruby never turns tail call recursion into loops. If you keep calling a function recursively, eventually you'll run out of memory.

9000
  • 39,899
  • 9
  • 66
  • 104
  • It's possible to make YARV support tail call optimization. See http://stackoverflow.com/questions/824562/does-ruby-perform-tail-call-optimization/824831#824831 – Andrew Grimm Sep 24 '11 at 14:10