Seven habits to improve the performance of Python programs

WBOY
Release: 2023-04-16 18:01:03
forward
649 people have browsed it

Seven habits to improve the performance of Python programs

1. Use local variables

Try to use local variables instead of global variables: to facilitate maintenance, improve performance and save memory.

Use local variables to replace variables in the module namespace, such as ls = os.linesep. On the one hand, it can improve program performance and make local variable searches 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, it is best to use isinstance(), followed by object type identity (id()), and object value (type()). Comparison is the worst.

#判断变量num是否为整数类型
type(num) == type(0) #调用三次函数
type(num) is type(0) #身份比较
isinstance(num,(int)) #调用一次函数
Copy after login

Do not put the contents of repeated operations as parameters in loop conditions to avoid repeated operations.

#每次循环都需要重新执行len(a)
while i < len(a):
statement
#len(a)仅执行一次
m = len(a)
while i < m:
statement
Copy after login

If you need to use a function or object Y in module X, you should directly use from X import Y instead of import X; X.Y. In this way, one query can be reduced when using Y (the interpreter does not have to first find the X module and then look up Y in the dictionary of the X module).

3. Use mapping instead of condition search

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

#if查找
if a == 1:
b = 10
elif a == 2:
b = 20
...
#dict查找,性能更优
d = {1:10,2:20,...}
b = d[a]
Copy after login

4. Direct iteration of sequence elements

For sequences (str, list, tuple, etc.), direct iteration of sequence elements is faster than the indexing of iterated elements. .

a = [1,2,3]
#迭代元素
for item in a:
print(item)
#迭代索引
for i in range(len(a)):
 print(a[i])
Copy after login

5. Use generator expressions to replace list comprehension

List comprehension (list comprehension) will generate an entire list, which will have a negative effect on iteration of large amounts of data. .

The generator expression does not, it does not actually create a list, but returns a generator that produces a value when needed (lazy calculation), which is more memory friendly.

#计算文件f的非空字符个数
#生成器表达式
l = sum([len(word) for line in f for word in line.split()])
#列表解析
l = sum(len(word) for line in f for word in line.split())
Copy after login

6. Compile first and then call

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

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

7. Module programming habits

The highest-level Python statement (code without indentation) in the module will be executed when the module is imported (regardless of whether it is really necessary to execute). Therefore, you should try to put all the function codes of the module into functions, including the function codes related to the main program, which can also be placed in the main() function, and the main program itself calls the main() function.

You can write test code in the main() function of the module. In the main program, check the value of name. If it is 'main' (indicating that the module is being executed directly), call the main() function and perform testing; if it is the module name (indicating that the module is being called), no testing will be performed. .

The above is the detailed content of Seven habits to improve the performance of Python programs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!