Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the habits of improving the performance of Python?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "what are the habits of improving the performance of Python?", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the habits of improving the performance of Python.

1. Use local variables

Replace variables in the module namespace with local variables, such as ls = os.linesep. On the one hand, it can improve the program performance and find local variables faster; on the other hand, short identifiers can be used to replace lengthy module variables to improve readability.

2. Reduce the number of function calls

When judging the object type, isinstance () is the best, the object type identity (id ()) is the second, and the object value (type ()) is the best.

# determine whether the variable num is of integer type

Type (num) = = type (0) # call the function type (num) is type (0) # identity comparison isinstance (num, (int)) # call the function once

Do not put the content of the repeated operation as a parameter in the loop condition to avoid repeated operation.

# each cycle requires re-execution of len (a) while I < len (a): statement#len (a) only once m = len (a) while I < m: statement

If you want to use a function or object Y in module X, you should directly use from X import Y instead of import X; X.Y. This reduces one query when using Y (the interpreter does not have to find the X module first and then look for Y in the dictionary of the X module).

3. Use mapping alternative condition to find

Maps (such as dict, etc.) search much faster than conditional statements (such as if, etc.). There is also no select-case statement in Python.

# if lookup if a = = 1: B = 10elif a = = 2: B = 20...#dict lookup, with better performance d = {1 10elif 10, 2 lance 20.} b = d [a]

4. Direct iterative sequence elements

For sequences (str, list, tuple, etc.), directly iterating sequence elements is faster than iterative elements.

A = [1JI 2pm 3] # iterative element for item in a: print (item) # iterative index for i in range (len (a)): print (a [I])

5. Use generator expression instead of list parsing

List parsing (list comprehension) produces the whole list, and iterating over a large amount of data has a negative effect.

The generator expression, on the other hand, does not actually create a list, but returns a generator that produces a value (deferred evaluation) when needed, which is more memory-friendly.

# calculate the number of non-empty characters in file f # generator expression l = sum ([len (word) for line in f for word in line.split ()]) # list parsing l = sum (len (word) for line in f for word in line.split ())

6. Compile before calling

When using eval () and exec () functions to execute code, it is best to call the code object (compiled into bytecode through the compile () function in advance) instead of calling str directly, which can avoid repeated compilation and improve program performance.

Regular expression pattern matching is similar, and it is also best to compile the regular expression pattern into a regex object (through the re.complie () function) before performing a comparison and match.

7. Module programming habits

The highest-level Python statements in the module (no indented code) are executed when the module is imported (import) (whether it is really necessary or not). Therefore, we should try to put all the functional code of the module into the function, including the functional code related to the main program can also be put into the main () function, and the main program itself calls the main () function.

You can write test code in the module's main () function. In the main program, the value of name is detected, and if it is' main' (indicating that the module is executed directly), the main () function is called to test; if it is the name of the module (indicating that the module is called), the test is not performed.

At this point, I believe you have a deeper understanding of "what are the habits of improving the performance of Python?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report