Simple ways to improve/optimize Python performance

1 Use built-in function when available

Use built-in function when available
Use built-in function when available

2 Use List comprehensions to Filter a list

Loop
Loop
Filter
Filter
List comprehensions
List comprehensions

3 Use “try” accordingly

# Slow
class Fruit(object):
    name='Apple'
    
fruit=Fruit()
    if hasattr(fruit,'name'):
        fruit.name
 
 
# Quicker
class Fruit(object):
    name='Apple'
    
fruit=Fruit()
    try:
        fruit.name
    except AttributeError:
        pass

4 Use “in” to check list rather than if (Use built-in function)

in vs for loop and if
in vs for loop and if

5 Deduplication

For loop and if vs set
For loop and if vs set

6 Sort

sorted
sorted
.sort()
.sort()

7 Put iterative loop into function

Iterative loop vs iterative loop in function
Iterative loop vs iterative loop in function

8 Check boolean

if var:
 
# Is faster than
 
if var is True:
 
# Is faster than
 
if var==True:

9 Check is the list is empty

if not list:
 
# Is faster than 
 
if list==[]:
 
# Is faster than
 
if len(list)==0:

10 Object vs list

list() and dict() are slower than [] directly returning a list.


Leave a Reply

Your email address will not be published. Required fields are marked *