> From: "Journeyer J. Joh" <oosaprogrammer at gmail.com> > I have a simple question about LLVM. > > I learned that we need to use iterations than recursions in C programming. > That is because recursion is expensive. It can easily consume out all > the stack given to a program. And the call/return consumes time much > more. > > But I've read a sentence that nowadays compilers can optimize > recursions in C or whatever languages not to consume heavy stack and > call/return. > > I wonder what kind of optimization this is and if LLVM support this > kind of optimization.At this point in your programming career, you should focus on writing clean, correct code. It's the same thing I'm supposed to focus on at this point in my own career! If the desired algorithm is expressed cleanly using recursion, use recursion (and procedure calls in general). If it's cleaner to use a loop, use a loop. The compiler will help when it can. Later, when you study compilers, you can learn exactly when and where the compiler can do various optimizations. Think about costs asymptotically; that's what matters. Calls and returns require constant time, just like addition and multiplication. Preston
Preston Briggs <preston.briggs at gmail.com> writes:> Think about costs asymptotically; that's what matters. Calls and > returns require constant time, just like addition and multiplication.Constant time, but not necessarily constant memory. Deep recursion will blow up your stack (AKA "segmentation fault" :-( ) if the compiler could not optimize it (tail recursion optimization). -- Matthieu Moy http://www-verimag.imag.fr/~moy/
On Wed, Oct 3, 2012 at 10:15 AM, Matthieu Moy <Matthieu.Moy at grenoble-inp.fr> wrote:> Preston Briggs <preston.briggs at gmail.com> writes: >> Think about costs asymptotically; that's what matters. Calls and >> returns require constant time, just like addition and multiplication. > > Constant time, but not necessarily constant memory. > > Deep recursion will blow up your stack (AKA "segmentation fault" :-( ) > if the compiler could not optimize it (tail recursion optimization).Only if the recursion is very deep. In practice, a recursive descent parser isn't going to run out of stack space, nor will a quicksort or binary-tree walker, You're distracting this man from his job of learning how to program. Yes, it's a mistake to have a set of mutually recursive routines that chew up all your stack space; but it's a mistake to reply on a compiler optimization to avoid such problems. Write an explicit loop if it's a possibility. Preston