loading...

When to choose purely functional programming?

patarapolw profile image Pacharapol Withayasakpunt ・1 min read

Especially for non-optimized programming languages, like JavaScript or Python. (Especially for the tail-call optimization part.)

What about the cost of creating a new Object? This is especially important for larger datasets, where performance matters. (Now, I am also thinking about Array generation performance)

Array.from({ length: 10e6 }).reduce((prev, c) => ...)

When the map / recursion isn't that big; maybe concepts from FP makes it easier to debug, but come with costs?

About the pure part, I realized that we are talking purely functional programming, not really that functional or procedural.

Discussion

markdown guide
 

Use pure functions when you want it to be maintainable. Use OO if that fits your mental model or enjoyment better. In most cases, performance will be good enough. Or at worst, you might have to optimize some fringe cases over time.

If performance is your goal, then it is exceedingly difficult to beat imperative/procedural written by someone who understands how the language works internally. They are basically bypassing the language and writing code to match the hardware constraints.

 

Why do you think that Javascript or python implementations are non-optimized?

To determine the cost of creating a new object (generally by allocating memory) on a given implementation, use a profiler.

Now compare it with the cost of extending an existing object (generally by ... allocating memory) on a given implementation, using a profiler.

In many cases you'll find that creating new objects is more cache friendly than extending sprawling trees, but ymmv.

In the end, the answer remains ... for performance, profile.

 

You're asking the right questions. It totally depends on your team and the lines of code. In my personal experience, if everybody has a solid FP background and the expected code size justifies the additional effort the paradigm causes in JS/PY, it is totally worth it.

Here are some background info on the aspects you mentioned (I am the author):

Trading Stack for Heap with Trampolines
Immutability in Languages w/o Purely Functional Data Types