When people first learn to code, their focus is—and should be—on getting their code to run properly. Their code is measured using one simple metric:
does the code actually work?
As software engineers gain more experience, though, they begin to learn about additional layers and nuances regarding the quality of their code. They learn that there can be two snippets of code that both accomplish the same task, but that one snippet is better than the other.
There are numerous measures of code quality. One important measure is code maintainability. Maintainability of code involves aspects such as the readability, organization, and modularity of one’s code.
However, there’s another aspect of high-quality code, and that is code efficiency. For example, you can have two code snippets that both achieve the same goal, but one runs faster than the other.
Take a look at these two functions, both of which print all the even numbers
from 2 to 100:
def print_numbers_version_one():
number = 2
while number <= 100:
if number % 2 == 0:
print(number)
number += 1
def print_numbers_version_two():
number = 2
while number <= 100:
print(number)
number += 2
Which of these functions do you think runs faster?
If you said Version 2, you’re right. This is because Version 1 ends up looping 100 times, while Version 2 only loops 50 times. The first version then, takes twice as many steps as the second version.
This blog is about writing efficient code. Having the ability to write code that runs quickly is an important aspect of becoming a better software developer.
The first step in writing fast code is to understand what data structures are and how different data structures can affect the speed of our code. So, let’s dive in.
DATA STRUCTURES
Let’s talk about data.
Data is a broad term that refers to all types of information, down to the most basic numbers and strings. In the simple but classic “Hello World!” program, the string "Hello World!" is a piece of data. In fact, even the most complex pieces of data usually break down into a bunch of numbers and strings.
Data structures refer to how data is organized. You’re going to learn how the same data can be organized in a variety of ways.
Let’s look at the following code:
x = "Hello! "
y = "How are you "
z = "today?"
print x + y + z
This simple program deals with three pieces of data, outputting three strings to make one coherent message. If we were to describe how the data is organized in this program, we’d say that we have three independent strings, each contained within a single variable.