logoalt Hacker News

a-dubyesterday at 9:19 PM4 repliesview on HN

lol. i once interviewed with facebook and had some "senior" dev on the phone who was balking and grousing at my claim that iterative algorithms are faster than recursive ones. the minute i mentioned spatial locality, he went quiet.

more to the point, i feel like there should be a compiler switch or decorator style flag in modern languages that declare "this function is expected to optimize with tail recursion, throw a compiler or linter error at static analysis time if that doesn't work out."


Replies

senkorayesterday at 9:22 PM

This exists in clang for C++ as the statement attribute [[clang::musttail]] and in gcc as [[gnu::musttail]]

dataflowyesterday at 9:46 PM

Re: your first paragraph, I don't get it, what does spatial locality have to do with recursion vs. iteration? And the blanket speed claim doesn't make sense either. I feel like you're thinking of a specific algorithm or access pattern or technology and overgeneralizing to the idea that it's somehow impossible for recursion to ever match the performance or be faster?

show 2 replies
palatayesterday at 9:55 PM

> more to the point, i feel like there should be a compiler switch or decorator style flag in modern languages that declare "this function is expected to optimize with tail recursion, throw a compiler or linter error at static analysis time if that doesn't work out."

Scala and Kotlin have that. Other modern languages probably do as well.

winstonleeyesterday at 9:38 PM

Been a while since I last used it but there is @tailrec in Scala. The compiler does enforce it and optimize the resulting bytecode.