Functional Programming – Compile Time Optimization Opportunities

compilationfunctional programming

I was reading the book "Functional Programming for the Real World". It started with comparison between imperative and functional programming languages. And it stated how 'values' and 'expressions' in functional programming is different from 'variables' and 'functions' of imperative programming. From the discussion I sort of developed an idea that –

Functional programming languages have more opportunity to do compile time optimization than their imperative counterparts.

Is it true?

Best Answer

Functional programming languages do much more compile time optimization. One of the reasons is purity - concurrency is trivial because there is no state. So the compiler can take two branches and concurrencize them easily without changing the behavior of the program.

At the same time, anything that can be calculated without state (ie anything non-monadic in haskell) can be calculated ahead-of-time by the compiler, but such calculations could be expensive and thus are probably only done partially.

Additionally, anything that isn't needed computationally can be completely optimzied out of the program.