Book Image

Scala High Performance Programming

By : Vincent Theron, Michael Diamant
Book Image

Scala High Performance Programming

By: Vincent Theron, Michael Diamant

Overview of this book

<p>Scala is a statically and strongly typed language that blends functional and object-oriented paradigms. It has experienced growing popularity as an appealing and pragmatic choice to write production-ready software in the functional paradigm. Scala and the functional programming paradigm enable you to solve problems with less code and lower maintenance costs than the alternatives. However, these gains can come at the cost of performance if you are not careful.</p> <p>Scala High Performance Programming arms you with the knowledge you need to create performant Scala applications. Starting with the basics of understanding how to define performance, we explore Scala's language features and functional programming techniques while keeping a close eye on performance throughout all the topics.</p> <p>We introduce you as the newest software engineer at a fictitious financial trading company, named MV Trading. As you learn new techniques and approaches to reduce latency and improve throughput, you'll apply them to MV Trading’s business problems. By the end of the book, you will be well prepared to write production-ready, performant Scala software using the functional paradigm to solve real-world problems.</p>
Table of Contents (13 chapters)

Tail recursion


A function is said to be recursive when it calls itself. Recursion is a powerful tool, and it is often used in functional programming. It allows you to break complex problems into smaller subproblems, making them easier to reason through and solve. Recursion also works well with the idea of immutability. Recursive functions provide us with a good way to manage changing state without using mutable structures or reassignable variables. In this section, we focus on the different shortcomings of using recursion on the JVM, and especially in Scala.

Let's take a look at a simple example of a recursive method. The following snippet shows a sum method that is used to calculate the sum of a list of integers:

def sum(l: List[Int]): Int = l match { 
  case Nil => 0 
  case x :: xs => x + sum(xs) 
} 

The sum method presented in the preceding code snippet performs what is called head-recursion. The sum(xs) recursive call is not the last instruction in the function...