Writing Code with Efficiency in Mind
Learn how to write efficient code with respect to time and memory consumption.
Efficient code
When we talk about efficient code, we can mean several different things. Let’s look at some of the things people might mean when they talk about efficient code.
Removing redundant or unnecessary code
You should always make sure that you remove redundant code. Redundant code is code that doesn’t affect the output of the application, but will be executed.
Take a look at the following code:
number = 10for i in range(1, 1000):number = number + inumber = 20print number
Here, we created the variable number
and set it to 10
.
Then, we have a for
loop. This loop will iterate 999
times. The first time this happens, the i
variable will have a value of 1
; the second time, it will be 2
, and so on until it reaches 1000
. Then, we’ll exit the loop.
Each time we’re inside the loop, we’ll take whatever value the variable number
currently has, add the current value of i
to it, and store the result in the number
variable.
After we exit the loop, we assign the value 20
to the variable number
, and by doing that, we’ll overwrite the value we just calculated.
This means that everything we did before the line where we assigned 20
to number
is unnecessary. Deleting those lines won’t have any effect on the output of the program, but when we run the application, this unnecessary loop will run, consuming some resources and wasting time.
Having code like this will also make the code harder to read because we’ll spend some time trying to figure out what the loop does and why it’s there.
With the unnecessary code removed, we can now see how we can use the computer’s hardware more efficiently.
Optimizing the use of memory and processors
It’s easy to waste memory without even ...