7 Good habits to improve the performance of a Python program

Source: Internet
Author: User
Tags generator

The original love coding, will program the nuclear power engineer. Personal blog Address: zhihu.com/people/zhong-yun-75-63

Learn some tricks to maximize the performance of Python programs and avoid unnecessary waste of resources.

1. Using Local variables

Try to use local variables instead of global variables: Ease of maintenance, improved performance, and memory savings.

Use local variables to replace variables in the module namespace, such as ls = Os.linesep. On the one hand, it can improve the performance of the program, local variable find faster, on the other hand, a short identifier can replace the lengthy module variable, improve readability.

2. Reduce the number of function calls

When the object type is judged, the isinstance () is optimal, followed by the object type identity (ID ()), and the object value (type ()) is used to compare the most time.

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

Avoid repeating operations by placing the contents of the repeating operation in the loop condition as a parameter.

#每次循环都需要重新执行len (a) while I < Len (a):   Statement#len (a) executes only once m = Len (a) while I < m:   statement

If you want to use a function or object Y in module X, you should use from X import y instead of import x directly; X.y. This allows you to reduce the query once you use Y (the interpreter does not have to find the X module first and then finds y in the dictionary of the X module).

3, using the mapping alternative conditions to find

Mappings (such as dict, etc.) are searched much faster than conditional statements (such as if, etc.). There are no select-case statements in Python.

#if查找if A = = 1:   b = 10elif A = = 2:   B = ... #dict查找, better performance d = {1:10,2:20,...} b = D[a]

4. Direct Iterative sequence elements

For sequences (str, list, tuple, and so on), the direct iteration of sequence elements is faster than the index of iterative elements.

A = [All-in-all] #迭代元素for item in a:   print (item) #迭代索引for I in range (Len (a)):  print (A[i])

5. Using Generator expression Substitution list parsing

List comprehension, which produces an entire list, has a negative effect on iterations of large amounts of data.

The generator expression does not, it does not actually create the list, but instead returns a generator that produces a value (deferred calculation) when needed and is more friendly to memory.

#计算文件f的非空字符个数 # generator expression l = SUM ([Len (word) for line in F for word in line.split ()]) #列表解析l = SUM (len (word) as line in F for Wo Rd in Line.split ())

6, first compiled after the call

When executing code using the eval (), exec () function, it is best to call the Code object (which is compiled into bytecode in advance via the compile () function) instead of directly calling STR, which avoids repeating the compilation process multiple times and improves program performance.

Regular expression pattern matching is also similar, and it is best to compile the regular expression pattern into a Regex object (via the Re.complie () function) before performing a comparison and matching.

7. Module Programming Habits

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

You can write the test code in the main () function of the module. In the main program, the value of name is detected, and if 'main' (indicating that the module is being executed directly), the main () function is called, and if the module name (which indicates that the module is called) is not tested.

7 Good habits to improve the performance of a Python program

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.