Hacker News new | ask | show | jobs
by Zelphyr 1081 days ago
Loops have the potential to be very inefficient. As an exercise you can write two scripts in Javascript, one that has a for loop and another that does the same thing functionally. Then you can use Node to dump the VM instructions. You might be surprised at how many fewer instructions the functional version requires.
2 comments

You have a cite or link exploring this?

I had thought tail-call optimization was a way to get inefficient recursion to parity with iteration, by turning it into iteration. I'd never heard of recursion being faster on its own.

Is it a javascript-specific thing due to how their int types work?

In von Neumann architectures, iteration will always be faster than recursion, because it'll need way less machine code. 2 caveats:

1rst one: It really depends on your data structure. If you use a tree, recursion will be faster on most operations (unless you optimize like crazy, but tbh, it's never worth it). Even with simple linked lists, some operations are better written with recursion.

2nd: more often than not, using first order functions will be both more efficient and easier to read than a for loop. If you're using a foreach loop to apply a function to each items, please use a map.

That is just untrue. Compilers tend to generate better code for imperative algorithms because current architectures implement a fundamentally imperative model. Yes, "sufficiently advanced" compilers can generate code that has similar performance to imperative algorithms from functional ones. But that requires some heavy lifting static analysis and optimisation passes. Have a look here: https://godbolt.org/z/sPT3snWE4. Only if you remove `#[inline(never)]` from `add1` will you get efficient code for the functional algorithm. This is a trivial example, but it ilustrates some of the nuances.