23.1 Introduction

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered.

— Donald Knuth.

Before you can make your code faster, you first need to figure out what’s making it slow. This sounds easy, but it’s not. Even experienced programmers have a hard time identifying bottlenecks in their code. So instead of relying on your intuition, you should profile your code: measure the run-time of each line of code using realistic inputs.

Once you’ve identified bottlenecks you’ll need to carefully experiment with alternatives to find faster code that is still equivalent. In Chapter 24 you’ll learn a bunch of ways to speed up code, but first you need to learn how to microbenchmark so that you can precisely measure the difference in performance.

Outline

  • Section 23.2 shows you how to use profiling tools to dig into exactly what is making code slow.

  • Section 23.3 shows how to use microbenchmarking to explore alternative implementations and figure out exactly which one is fastest.

Prerequisites

We’ll use profvis for profiling, and bench for microbenchmarking.

library(profvis)
library(bench)