My favorite programming task is optimization. Usually that means making some code system run faster, though sometimes I’m optimizing memory usage or network bandwidth or some other resource.

It’s my favorite task because it’s simple to measure success. For most coding work, what constitutes success is fuzzy. Books like this one try hard to define what good code or a good system looks like, but what makes a line of code good is always imprecise.

That’s not true for optimization. There, the answers are crisper. If you’re trying to make something run faster, you can measure your success directly. The same goes for the cost of that success in terms of increased code size or complexity. No worrying about semi-defined long-term benefits, no trusting that someone reading your new code a few years from now will understand it immediately and be swept away in a wave of emotional appreciation for you as a programmer. Just immediate, tangible results.

I’m not alone in this fondness for optimization. In fact, it’s seductive enough to have prompted the one programming adage that every programmer knows:

Premature optimization is the root of all evil.

That’s not the whole quote, by the way. The original version, as written down by Donald Knuth in 1974, is more nuanced:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

It’s important to note the context. 1 In 1974, compilers were much less sophisticated than they are now. The “small efficiencies” Knuth talks about were often tricky little bits of code to get the compiler to generate the code you wanted, like caching end points to eke out a little bit of performance:

int stripNegativeValues(int count, int * data)
{
    int * to = data;

    for (int * from = data, * end = data + count; 
         from < end; 
         ++from)
    {
        if (*from >= 0)
            *to++ = *from;
    }

    return to - data;
}

Or using macros to avoid the cost of a function call: 2

typedef struct
{
    float x, y, z;
} Vector;

#define dotProduct(A, B) (A.x * B.x + A.y * B.y + A.z * B.z)

Fortunately , these days the compiler is smart enough to generate the right instructions for your source code, at least if you’re writing simple and straightforward code. The trickier you try to get, the less likely it is that the compiler will be able to figure out what you mean, so old-school tricks and extravagant C++ magic often end up generating worse code than just writing out the simplest expression of your logic.

Having smart compilers hasn’t saved us from ourselves, though. It’s instinctive in programmers to worry about resources, whether that’s time or storage or bandwidth—and that can lead to trying to solve performance problems before they pop up.

Let’s say you’re choosing a random item from a list, something games do a lot. The items aren’t equally likely—each has a weighted chance of being chosen :

template <class T>
T chooseRandomValue(int count, const int * weights, const T * values)
{
    int totalWeight = 0;
    for (int index = 0; index < count; ++index)
    {
        totalWeight += weights[index];
    }

    int selectWeight = randomInRange(0, totalWeight - 1);
    for (int index = 0;; ++index)
    {
        selectWeight -= weights[index];
        if (selectWeight < 0)
            return values[index];
    }

    assert(false);
    return T();
}

This is pretty simple. Sum up all the weights, then choose a random number no larger than the sum. As you subtract weights, one of them will cause the sum to go negative, selecting that weighted value. The chance of that happening is proportional to the weight—done!

But it’s easy to look at this and decide it could be faster. The second loop through the values doesn’t seem necessary. If you hang on to the running sum of weights, you could divide-and-conquer your way to the answer, making the second loop much faster:

template <class T>
T chooseRandomValue(int count, const int * weights, const T * values)
{
    vector<int> weightSums = { 0 };
    for (int index = 0; index < count; ++index)
    {
        weightSums.push_back(weightSums.back() + weights[index]);
    }

    int weight = randomInRange(0, weightSums.back() - 1);

    int minIndex = 0;
    int maxIndex = count;

    while (minIndex + 1 < maxIndex)
    {
        int midIndex = (minIndex + maxIndex) / 2;
        if (weight >= weightSums[midIndex])
            minIndex = midIndex;
        else
            maxIndex = midIndex;
    }

    return values[minIndex];
}

This is a rookie mistake. Actually, it’s a whole list of rookie mistakes all nested inside each other. Yes, the second loop is O(log N) now, not linear, but that doesn’t really matter when the first loop is still linear. You haven’t made a dent in overall performance.

Even that isn’t really the issue. Unless you know that you’ve got a lot of weighted random choices, the simple linear loop is going to be faster. Until you get to 200(!) or so choices, the linear loop is faster than the binary search, at least as measured on my PC. That’s a bigger number than you would have guessed, right? Up until that point, simpler logic and better memory-access patterns trump algorithmic efficiency.

But that’s not the real issue, either. It doesn’t matter how fast you do the lookup—the second version allocates memory, which is much slower than anything else you do. If you actually run the two functions as written earlier, the first version is twenty times faster than the second one. Twenty times!

Wait—that’s still not the real issue! The real issue is that it doesn’t matter how fast chooseRandomValue is, as you would quickly learn with a little bit of profiling. You might call it hundreds of times every second, but the profiler would tell you it represents a meaningless fraction of your overall runtime. The Sucker Punch engine has functions that are called millions of times every second; if you’re writing a game, you do too. When it comes to performance, those functions matter, and chooseRandomValue doesn’t .

The First Lesson of Optimization

So that’s the first lesson of optimization— don’t optimize.

Make your code as simple as possible. Don’t worry about how fast it will run. It’ll be fast enough. And if it’s not, it will be easy to make it fast. That last bit—that it will be easy to make simple code fast—is the second lesson .

The Second Lesson of Optimization

Imagine you’ve got some simple, solid code that you took ordinary care writing. Your section of the project is running a little slow, so you instrument it and discover that this small bit of code is soaking up half of your performance.

This discovery is great news! If you can fix the performance of that one bit of code, you can double your overall performance.

This is pretty typical, by the way. The first time you look at the performance of some bit of code that’s never been optimized, there’s invariably good news. It’s obvious what you need to work on.

Bad news would be discovering that nothing is obviously slow, but that’s rare for code that hasn’t survived a few rounds of optimization.

Here’s a rule of thumb—if you’ve never optimized some bit of code, you can make it five to ten times faster without a lot of work. That may seem optimistic, but it isn’t. In practice, there’s lots of low-hanging fruit in unoptimized code.

Putting the Second Lesson to the Test

Let’s put that rule of thumb to the test. Imagine that I was wrong about choo⁠se​RandomValue . It’s getting called so often, and with so many choices, that it’s actually taking up half of your processor time.

Now, if you were starting with the second implementation, my rule of thumb would be easy to prove. Just switch to a simpler, no-allocation model like your first implementation and it runs 20 times faster. Rule of thumb proven!

That’s too easy, though. Let’s assume you’re starting with the first implementation, so you don’t have the easy solution of removing memory allocation. That’s a bit unrealistic, actually—usually the first thing you discover when you look at performance is that someone is allocating memory inside a loop, and it’s easy to fix. But let’s assume you got unlucky and it’s not something simple.

Here’s a five-step process for optimizing something. I’m going to focus on performance (“processor time,” to be explicit), but the same steps work for any resource. Just substitute network bandwidth, memory usage, power consumption, or whatever measurable thing you’re trying to optimize for in the following steps.

Step 1: Measure and Attribute Processor Time

That is, measure how much processor time is being spent and attribute it to functions, or objects, or whatever is convenient. In the preceding example, I must have done this already because I know that chooseRandomValue is consuming half of my processor time.

Step 2: Make Sure There’s Not a Bug

It’s pretty common to find out that what looks like a performance problem is actually a bug. In this case, with chooseRandomValue actually soaking up half of your cycles, I would strongly suspect a bug somewhere. I’d look pretty hard at whether all of these calls to chooseRandomValue are appropriate.

Maybe someone is getting a loop condition wrong and a counter is wrapping all the way around. Instead of a handful of iterations, it’s looping 2 32 times, plus or minus. That’s a lot of calls to chooseRandomValue ! (And yes, I’ve fixed this exact bug.)

Step 3: Measure Your Data

Don’t even think about optimizing until you know what your data looks like. How many calls are made to chooseRandomValue ? How many options are you choosing between? Are you repeatedly choosing from a small number of weighted distributions, or is it less predictable? How many zero weights are in the list? Do the lists of values you’re choosing from have repeated values?

Most optimizations exploit some aspect of the data or how you use it. You can’t make good decisions about optimization without thoroughly understanding the shape of your data.

Step 4: Plan and Prototype

If your optimization worked perfectly—if it drove processor time all the way to zero—then what would overall performance look like? In this case, that would mean that chooseRandomValue ran in zero time. If it did, would you hit your performance target?

If not, then your plan isn’t good enough. You’ll need to identify other bits of code that can be optimized. Don’t start working on an optimization until you know it’s part of a plan that can succeed.

Sometimes it’s hard to project what overall performance will look like with a perfect optimization. Code interacts with other code in unpredictable ways. Maybe chooseRandomValue is pulling weight values into the processor’s data cache, and some other function is also using those values. In the worst case, you drive chooseRandomValue to zero cycles and overall performance doesn’t change. The core problem was loading the weight values into the data cache—you’ve just shifted the blame to a new culprit.

Look for an opportunity to prototype your optimization. In this case, maybe you can just have chooseRandomValue return the first value in the list of choices every single time. That’s not correct, but it’s likely to give you a good idea of what performance would be with a perfectly optimal solution.

Step 5: Optimize and Repeat

Once you’re through the first four steps, you can start thinking about optimization. You’ve got ideas about how expensive various parts of the code ought to be, based on how much logic is involved and how much memory is accessed. Maybe some of this code or memory access could be simplified or skipped. If there’s not some simple way to speed up the code, look for things you can exploit in the data. For instance, if most of the weights passed to chooseRandomValue are zero, you can exploit that. If there are duplicate values, then that might be something you can work with.

Don’t just dive in, though. A one-step optimization plan of “look for some bit of code that looks slow and make it faster” is not going to work. Your instincts are wrong about where the problem is, they’re wrong about what the data looks like, and they’re wrong about what the right fix will be. 3

Once you’ve completed Step 5, measure your performance again. If you’ve hit your target, great! Declare victory and stop optimizing. Otherwise, back to Step 1 you go. Some of the steps may go more quickly the second time through, but it’s worth pausing at each of them to think about what you’ve learned so far.

Applying the Five-Step Optimization Process

OK, I’m ready to apply the process! I’m setting aside the word processor and firing up the development environment. I’ll start with the first implementation of chooseRandomValue , apply the five-step optimization process, and see how much effort it takes to get a 10x speedup.

The first implementation of chooseRandomValue is a solid example of taking ordinary care while writing code—it’s optimized for simplicity and clarity, which is always the place to start. If my rule of thumb is correct, then I should be able to get a 5x to 10x speedup without too much work.

I admit to a bit of nervousness as I type this. This has the potential to be really embarrassing.

I’ve already done Step 1—I know that I’m spending half of my cycles in chooseRandomValue .

For Step 2, I put in a gallant effort but don’t find any bugs. All the callers have legitimate reasons to call, and they’re not doing anything obviously wrong.

In Step 3, I discover the problem—I’m making a lot of calls to chooseRandomValue and in most cases passing long lists of weights and values. The data looks pretty random, though the weights are small. Most of the values are less than 5 and none is greater than 15. Interestingly, there are lots of calls, but they’re all from a small, static number of distributions—that is, the same lists of thousands of weights and values are getting passed over and over.

For Step 4, I create a perfect-performance version of chooseRandomValue . In this case, I substitute a version that returns a random value from the list while ignoring the weights—hard to imagine anything simpler than that. You could just return the first value in the list, but that would skip the random-number generation call that seems inevitable, so returning an unweighted random choice seems like a better prototype.

I’m testing it now…and the code runs roughly 50 times faster than my baseline implementation. Looks like there’s room for the 5x to 10x speedup I predicted. On to Step 5—making the code run faster!

Your first impulse when you need to make code run faster might be to actually, you know , make the code run faster . Do the same stuff, just do it faster: unroll a loop, use multimedia instructions to process multiple entries at once, write some assembly language, move some bit of math outside a loop.

That’s a bad impulse. Those sorts of optimizations are the last thing you should try, not the first thing. In the two million or so lines of code in Ghost of Tsushima , there are only a few dozen places where we’ve done those sorts of microoptimizations. It’s not that we don’t spend a lot of effort optimizing—everything we do has to complete in a sixtieth of a second, after all. 4 We sweat bullets to get the game to run that fast. But with rare exceptions, doing the same thing faster isn’t how we improve performance.

The way to make code run faster is to do less, not to do the same things faster. Figure out what the code is doing that it doesn’t need to be doing, or what it’s doing multiple times that could be done once. Eliminate those bits of code and things will run faster.

In this case, an obvious candidate is calculating the total weight for a distribution. In the first implementation of chooseRandomValue I’m doing that on every call…but when I measured the data in Step 3 I discovered that I was generating random values from a limited number of distributions. I could easily calculate the total weight once for each distribution, then reuse it in choose​Ran⁠domValue :

struct Distribution
{
    Distribution(int count, int * weights, int * values);

    int chooseRandomValue() const;

    vector<int> m_weights;
    vector<int> m_values;
    int m_totalWeight;
};

Distribution::Distribution(int count, int * weights, int * values) :
    m_weights(),
    m_values(),
    m_totalWeight(0)
{
    int totalWeight = 0;

    for (int index = 0; index < count; ++index)
    {
        m_weights.push_back(weights[index]);
        m_values.push_back(values[index]);

        totalWeight += weights[index];
    }

    m_totalWeight = totalWeight;
}

int Distribution::chooseRandomValue() const
{
    int select = randomInRange(0, m_totalWeight - 1);

    for (int index = 0;; ++index)
    {
        select -= m_weights[index];
        if (select < 0)
            return m_values[index];
    }

    assert(false);
    return 0;
}

Allocating memory is expensive—that’s why the ill-fated first attempt to optimize chooseRandomValue failed. It allocated memory on every call, which completely dominated the overall cost of the function. Here, though, I’m only doing the allocation once per distribution, not once per call. If I was creating new distributions all the time then these allocations would be a disaster, but I know from Step 3 (where I measured the data) that I’ve got a relatively short list of distributions. Allocating a chunk of memory for each distribution in that short list is fine.

I run the code again…and it’s about 1.7 times faster than the baseline. Encouraging, but not a complete victory. If you think about the math here, though, you’ll realize that at best I might have hoped for a 3x speedup. I walked through the list of weights 1.5 times on average before—all the way through once to calculate the total weight, then on average halfway through to look up the random value. Now I’m only doing the lookup.

The difference is the memory access. Before, the full pass through the weights pulled them all into some level of the data cache, so the second lookup pass had quick access to them. Now it takes more time for the second pass to retrieve the values, so I get a 1.7x speedup instead of a 3x speedup.

There’s an obvious next step—now that memory allocation is plausible, a binary search makes more sense. That isn’t hard to get right, just a bit fiddly:

struct Distribution
{
    Distribution(int count, int * weights, int * values);

    int chooseRandomValue() const;

    vector<int> m_weights;
    vector<int> m_values;
    vector<int> m_weightSums;
};

Distribution::Distribution(int count, int * weights, int * values) :
    m_weights(),
    m_values(),
    m_weightSums()
{
    int totalWeight = 0;

    for (int index = 0; index < count; ++index)
    {
        m_weights.push_back(weights[index]);
        m_values.push_back(values[index]);
        m_weightSums.push_back(totalWeight);

        totalWeight += weights[index];
    }

    m_weightSums.push_back(totalWeight);
}

int Distribution::chooseRandomValue() const
{
    int select = randomInRange(0, m_weightSums.back() - 1);

    int minIndex = 0;
    int maxIndex = m_weights.size();

    while (minIndex + 1 < maxIndex)
    {
        int midIndex = (minIndex + maxIndex) / 2;
        if (select >= m_weightSums[midIndex])
            minIndex = midIndex;
        else
            maxIndex = midIndex;
    }

    return m_values[minIndex];
}

Testing this attempt…and it’s about 12 times faster than the baseline. Rule of thumb validated! Imagine an audible sigh of relief from the author here as I return, vindicated, to the word processor.

Most of the time a 12x speedup is enough. Once you’ve picked the low-hanging fruit, move on to other things. Resist the temptation to keep optimizing. It’s easy to get caught up in the joy of tangible success and chase more performance wins you don’t need. The function that was a performance problem is no longer a performance problem. At this point it’s no different than any other function in the project. It doesn’t need more optimization .

Look, I’m dealing with that temptation right now. I’ve got more ideas about how chooseRandomValue could be faster. I’m curious about which ones will actually work, and I’m fighting the urge to satisfy that curiosity. But the right thing to do once you hit your performance target is to add your optimization ideas as comments to the code, then set it aside. Declare victory and move on .

There’s an obvious question that I haven’t addressed. The first lesson of optimization was “Don’t optimize,” right? Take ordinary care, write simple and clear code, and trust that if you need to be able to make the code 5 to 10 times faster it will be easy to do so.

But what if 5 to 10 times faster isn’t enough? What if you make a huge mistake in your initial design for a system, a mistake big enough that you need things to be 100 times or 1,000 times faster ?

There Is No Third Lesson of Optimization

You might argue that there’s a third lesson of optimization: “But don’t do anything stupid.” If you’re going to build a high-frequency trading application where microseconds matter, then don’t build it in Python. If you’re defining some result structure you’re going to be passing around all over your C++ code, don’t design it so every copy does a memory allocation.

Honestly, I think the third lesson doesn’t exist. Programmers worry too much about performance, full stop.

I get it. I have the same weakness. I’ll build complexity into code for the sake of performance without a shred of evidence that performance will matter. I catch myself doing this All. The. Time.

Maybe the third lesson is “Don’t worry about making mistakes, because you won’t be able to make mistakes you can’t fix.”

If you do write your high-frequency trading app in Python and then run into trouble, there’s still hope. Convert the stuff that needs to go fast to C++ and leave the stuff that can go slow in Python. Converting from Python to C++ will get you (another rule of thumb) a 10x speedup, and per our experiment in this Rule, we can expect an easy 5x to 10x speedup once it’s in C++. Presto, a 50x to 100x speedup.

This is a pretty frequent upgrade path for us at Sucker Punch, actually—writing the first version of something in our lovely but relatively slow scripting language, then converting it to C++ if it becomes a bottleneck. We get the benefits of trying ideas quickly, knowing that there’s an escape path to better performance if that proves necessary.

Remember, if you actually make a mistake so bad that you’ll need to find a 100x performance win, then you’re going to know about it early. Mistakes that bad don’t lurk in the weeds. They’re obvious from the start, so you’re not going to get in too deep before you discover them. So, again, don’t worry about them .

Trust in the two lessons of optimization. Write simple and clear code, and trust that solutions will appear for any performance problems you run into.

1 The origin of the quote is disputed, though Knuth’s version is the first known published form of it. It’s also attributed to Tony Hoare, who thought it sounded more like something Edsger Djikstra would have said. All three parties appear to be unsure of the actual origin, attributing it to common folk wisdom at the time. This is the perfect recipe for an unending argument on the internet.

2 Note the archaic syntax here, which I threw in to take the old-timers down Memory Lane.

3 Unless your instinct is that someone is allocating memory somewhere. Then you’re probably right.

4 Or thirtieth of a second, depending on the game. I’m not committing us to any specific performance numbers for future games, mind you.