Home Artificial Intelligence 5 Code Optimization Techniques To Speed Up Your Programs

5 Code Optimization Techniques To Speed Up Your Programs

0
5 Code Optimization Techniques To Speed Up Your Programs

Make your code more efficient and skilled with these language-agnostic methods

Towards Data Science
Photo by Shubham Dhage on Unsplash

Make it work first, then make it fast. That is one common principle many skilled programmers go by. At first, you could write your code using whichever approach seems essentially the most intuitive to save lots of development time on the draft. After you bought a working implementation, you could wish to optimize it by fastidiously selecting which techniques data structures work best in your specific case.

In this text, we’ll explore five language-agnostic methods you should utilize to enhance your code runtime. The next concepts are generic and might be applied to any programming language.

Loop-invariant extraction

Consider the next Python code that checks a listing of strings against a daily expression to search out all of the matches:

import  as re

# Get some strings as input
strings = get_strings()
# List to store all of the matches
matches = []

# Iterate over the input strings
for string in strings:

# Compile the
rex = re.compile(r'[a-z]+')

# Check the string against the
matches = rex.findall(string)

# Finally, append the matches to the list
matches.extend(matches)

Loops repeatedly apply a set of instructions to a various input. With this in mind, can you notice any operation that doesn’t change within the code above?

The statement `rex = re.compile(r’[a-z]+’)` operates on a relentless input: the string. For each iteration of the loop, this statement does the exact same thing, independently from the loop’s input. If we were to extract this invariant statement and execute it once before the loop, the code would still have the identical overall behavior while saving some CPU cycles.

import  as re

# Get some strings as input
strings = get_strings()
# List to store all of the matches
matches = []

# Compile the just once before the loop
rex = re.compile(r'[a-z]+')

# Iterate over the input strings
for string in strings:

# Check the string against the
matches = rex.findall(string)

# Finally, append the matches to the list
matches.extend(matches)

LEAVE A REPLY

Please enter your comment!
Please enter your name here