Pure vs Impure Functions Performance

ยท ยท 425 words ยท 2 minute read

I read this post on dev.to and wondered if functional proramming and pure functions makes your code slower or faster. So, I want to know that.

The impure implementation of fizzbuzz in Javascript ๐Ÿ”—

I used the javascript code from that articles of impure implementation of fizzbuzz and timed its execution by this command time node fizzbuzz-impure.js.

for (let i = 1; i <= 1000000; i++) {
    if (i % 15 === 0) console.log('FizzBuzz');
    else if (i % 3 === 0) console.log('Fizz');
    else if (i % 5 === 0) console.log('Buzz');
    else console.log(i);
}

The execution time of impure fizzbuzz ๐Ÿ”—

1: node fizzbuzz-impure.js  5.53s user 0.89s system 95% cpu 6.709 total
2: node fizzbuzz-impure.js  5.37s user 0.89s system 94% cpu 6.640 total
3: node fizzbuzz-impure.js  5.17s user 0.78s system 94% cpu 6.272 total
4: node fizzbuzz-impure.js  5.24s user 0.79s system 95% cpu 6.347 total
5: node fizzbuzz-impure.js  5.21s user 0.81s system 94% cpu 6.342 total
Average : 5.304 seconds

The pure implementation of fizzbuzz in Javascript ๐Ÿ”—

I used the javascript code from that articles of pure implementation of fizzbuzz and timed its execution by this command time node fizzbuzz-pure.js.

const divisible = x => y => x % y === 0
const range = (min, max) => Array.from({ length: max - min + 1 }, (_, i) => min + i)

const reduce = f => init => xs => xs.reduce(f, init)
const map = f => xs => xs.map(f)
const forEach = f => xs => xs.forEach(f)

const CANONICAL_FIZZBUZZ = [
    {n: 3, str: 'Fizz'},
    {n: 5, str: 'Buzz'},
];

const fizzbuzz = keys => i => {
    const divisibleI = divisible(i);
    const reducer = reduce((acc, {n, str}) => acc + (divisibleI(n) ? str : ''))('');

    return reducer(keys) || i;
};

const canonFizzbuzz = fizzbuzz(CANONICAL_FIZZBUZZ);
const mapFizzbuzz = map(canonFizzbuzz);

// IMPURE CODE STARTS HERE
const print = x => console.log(x)
const printEach = forEach(print);
printEach(mapFizzbuzz(range(1, 1000000)))

The execution time of pure fizzbuzz ๐Ÿ”—

1: node fizzbuzz-pure.js  5.39s user 0.83s system 94% cpu 6.550 total
2: node fizzbuzz-pure.js  5.41s user 0.85s system 94% cpu 6.596 total
3: node fizzbuzz-pure.js  5.38s user 0.80s system 95% cpu 6.510 total
4: node fizzbuzz-pure.js  5.53s user 0.82s system 95% cpu 6.656 total
5: node fizzbuzz-pure.js  5.39s user 0.81s system 95% cpu 6.531 total
Average : 5.42 seconds

Pure functions vs impure functions performance ๐Ÿ”—

Pure functions help in code management and re-usability not in performance. The performance of pure functions is almost equal to impure functions. But sure, the impure functions can be faster by a thin margin.

Share: