Better Programming

Advice for programmers.

Follow publication

Member-only story

Get Rid of Excessive If-Else Statements With Lookup and Hash Tables

Nicholas Obert
Better Programming
Published in
5 min readNov 1, 2021

--

Photo by matthew Feeney on Unsplash

If-else statements are a staple of programming, we learn to use them since we start our journey. While they are a great tool, they aren’t always the best choice. For instance, take a look at this stupid Python code example:

This if-else sequence is not only unnecessarily bulky, but also pretty inefficient. Moreover, if you had to perform more operations than just calling a function, this code pattern would get very messy.

As regards execution speed, checking all those if statements’ conditions in series would mean that, for example, if the chosen character is the last (the Dragon), the program would go through every other case before finding the correct one. Expressing it with the big O notation, used to classify algorithms by their speed or space requirements as the input size grows, a sequence of if-else statements would be classified as O(n/2), or simply O(n). This means that the time it takes to execute that code grows linearly as the number of cases to check increases. So, imagine having much more characters to choose from. How much time would it take to check all those cases? Unnecessarily long.

What Are Lookup and Hash Tables?

Lookup tables and hash tables are data structures that can replace computations during runtime with a simple lookup, be it a simple array indexing or through a hash function. Such tables trade memory with execution speed since they already store the computation’s result.

Talking about time complexity, indexing a lookup table scores a constant O(1) or in simple words, no matter how many cases are possible, it will always take the same amount of time to get the result. Hash tables also score, on average, O(1) and in the worst case, although very rare, O(n). This said lookup and…

--

--

Nicholas Obert
Nicholas Obert