Scala – Function vs Procedural quick sort performance comparison

Scala is becoming dominant in many scalable, distributed framework \ toolset. Kafka, Spark, Akka are developed in Scala. I recently had to used both Kafka and Spark, and understanding Scala make it easy to debug the framework code. So i started learning Scala. I am reading Scala By Example. 

One of first example is quick sort. In that author Martin Odersky describe the imperative (i call it procedural) way vs functional way. Martin explains – “But
where the imperative implementation operates in place by modifying the argument array, the functional implementation returns a new sorted array and leaves the argument array unchanged. The functional implementation thus requires more transient memory than the imperative one.”

So I wanted to find out how performance and memory usage between the 2 approaches. The code is checked in @

The output for arraySize (10, 100, 1000, 10000, 100000, 1000000, 50000000) is

array size – 10
Functional Sort Time : 64
Procedural Sort Time : 0
array size – 100
Functional Sort Time : 13
Procedural Sort Time : 0
array size – 1000
Functional Sort Time : 59
Procedural Sort Time : 1
array size – 10000
Functional Sort Time : 75
Procedural Sort Time : 2
array size – 100000
Functional Sort Time : 344
Procedural Sort Time : 12
array size – 1000000
Functional Sort Time : 2159
Procedural Sort Time : 104
array size – 50000000
Functional Sort Time : 112694
Procedural Sort Time : 6390

Below is jconsole snapshot for final run of array size of 50000000. The red highlighted point indicate where the Functional sort completes and the Procedural sort starts. ( I put readline between 2 executions, so i wait for few seconds before 2nd execution). So as obvious we see memory usage in 1.5Gb in functional style vs 0.3Gb in procedural style. Also CPU hovers around 25% for entire duration of functional style.

I am still learning about Scala. I believe Author’s reason for putting this in the beginning it to caution developers to being mindful of where to use procedural \ object oriented way and where to use functional way.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s