> For comprehensions can also cause some overhead, so if you're really pressed for performance a while loops is always an option.
In most cases in which I need a while loop, I use a tail recursion instead. You can keep your code free of side-effects that way and the compiler generates code equivalent to a while loop.
> In most cases in which I need a while loop, I use a tail recursion instead. You can keep your code free of side-effects that way and the compiler generates code equivalent to a while loop.
Hear, hear! I can corroborate this statement and have benchmarked it quite a bit in the past. If you can mark a method as @tailrec in scala and the compiler does not complain, it will go as fast as if it were written with a while loop. And in many cases it will feel cleaner as well.
Of course, not everything writes itself nicely in a recursive style, for this you should use while if you need the performance. Don't be afraid, scala is after all a mariage between OO, functional and bits and pieces of everything nice. It's still there for a reason.
* the @tailrec attribute is not necessary but forces the compiler to complain when your recursive method is not, in fact, tail recursive. It's also good documentation that a developer who makes changes should keep it tail recursive because it's sensitive.
In most cases in which I need a while loop, I use a tail recursion instead. You can keep your code free of side-effects that way and the compiler generates code equivalent to a while loop.