Fundamentals 6 min read

7 Proven Python Tricks to Boost Performance and Save Resources

Learn seven practical Python optimization techniques—from using local variables and reducing function calls to leveraging generators and pre-compiling code—that can noticeably improve execution speed, lower memory usage, and make your scripts more efficient.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
7 Proven Python Tricks to Boost Performance and Save Resources

Master some techniques to improve Python program performance and avoid unnecessary resource waste.

1. Use Local Variables

Prefer local variables over globals: easier maintenance, better performance, and memory savings.

Replace module namespace variables with locals, e.g., ls = os.linesep. Local variable lookup is faster and shorter identifiers improve readability.

2. Reduce Function Call Frequency

When checking object types, isinstance() is optimal, followed by identity comparison with id(), and finally type() comparison.

# Determine if variable num is an integer type
type(num) == type(0)  # calls three functions
type(num) is type(0)  # identity comparison
isinstance(num, int)  # single function call

Avoid placing repeated operations in loop conditions; compute them once before the loop.

# Recalculate len(a) each iteration (inefficient)
while i < len(a):
    statement

# Compute length once (efficient)
m = len(a)
while i < m:
    statement

Import specific objects directly: from X import Y instead of import X; X.Y to save a lookup.

3. Use Mapping Instead of Conditional Chains

Dictionary lookups are much faster than multiple if/elif statements.

# if-elif chain (slow)
if a == 1:
    b = 10
elif a == 2:
    b = 20
# ...

# dict lookup (fast)
d = {1: 10, 2: 20, ...}
b = d[a]

4. Iterate Directly Over Sequence Elements

Iterating over items is faster than iterating over indices.

a = [1, 2, 3]
# iterate items
for item in a:
    print(item)

# iterate indices (slower)
for i in range(len(a)):
    print(a[i])

5. Prefer Generator Expressions Over List Comprehensions

List comprehensions build the whole list in memory, while generator expressions produce items lazily, reducing memory usage.

# generator expression
l = sum(len(word) for line in f for word in line.split())

# list comprehension (creates full list)
l = sum([len(word) for line in f for word in line.split()])

6. Compile Before Execution

When using eval() or exec(), compile the code string first with compile() to avoid repeated compilation.

Similarly, compile regular expression patterns with re.compile() before matching.

7. Module Programming Practices

Place executable code inside functions; only top‑level statements run on import. Wrap script logic in a main() function and call it under if __name__ == '__main__': to keep imports lightweight and enable testing.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

performanceoptimizationPythonbest-practicescode
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.