DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on

When to choose purely functional programming?

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) => ...)
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (3)

Collapse
 
kspeakman profile image
Kasey Speakman

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.

Collapse
 
pentacular profile image
pentacular

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.

Collapse
 
iquardt profile image
Iven Marquardt • Edited

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