0

I looked at this question trying to better understand @tailrec annotation in scala.

What I'm not sure is whether the annotation also hints the compiler to do some optimizations or it's only used for warnings when you mark a method that is not a tail-recursion?

More specifically - is this annotation might affect performance in any way? For example, if I don't put this annotation, the compiler will compile a tail-recursive function as non-tail recursive?

Community
  • 1
  • 1
Avi
  • 21,182
  • 26
  • 82
  • 121
  • Looking at [this answer specifically](http://stackoverflow.com/a/3114245/135978) it does appear that the Scala compiler will automatically optimize a method it determines is tail-recursive - the annotation is only used to signal to the compiler that you *expect* this method to be able to participate in those optimizations. – Sean Vieira May 08 '14 at 15:40
  • I thought so too, but I wasn't sure. Also after speaking with a colleague that lowered my confidence I decided to verify it. – Avi May 08 '14 at 15:41
  • 2
    Beware that if there are multiple recursion points and only some (even just one) of them is tail-recursive but others are not, the compiler will not flag it as an error when `@tailrec` is used. – Randall Schulz May 08 '14 at 16:38

1 Answers1

4

As per the scaladoc:

A method annotation which verifies that the method will be compiled with tail call optimization.

If it is present, the compiler will issue an error if the method cannot be optimized into a loop.

This is a verification to trigger an error if you thought you wrote an optimizable function while you actually did not. Even if you don't put it, the compiler will optimize the code if it is possible.

vptheron
  • 7,426
  • 25
  • 34