Size: 3237
Comment:
|
Size: 3235
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 10: | Line 10: |
== String Concatenation == | = String Concatenation = |
Python性能调试笔记
::-- Roka [DateTime(2007-04-26T14:46:55Z)] TableOfContents
1. String Concatenation
(1)
Normal Code:
Optimized Code:
1 s = "".join(list)
(2)
Normal Code:
Optimized Code:
(3)
Normal Code:
1 out = "<html>" + head + prologue + query + tail + "</html>"
Optimized Code:
1 out = "<html>%(head)s%(prologue)s%(query)s%(tail)s</html>" % locals()
1.1. Loops
(1)Converting to upper case:
Normal Code:
Optimized Code:
1.2. OOP
(1)Suppose you cannot use map() or list comprehension, just remember Avoiding dots:
1.3. Local Variables
(1)Final speedup method is to use local instead of global vars.
1.4. Dictionary
(1)Avoid if in for loops:
Normal Code:
Optimized Code:
Also , if the value stored in the dict is an object or a list, you could also use the dict.setdefault method, e.g.
1 wdict.setdefault(key, []).append(newElement)
This avoids having to lookup the twice.
1.5. Import
(1)import inside the function is more efficiently.
(2)Do import once,
1.6. Data Aggregation
(1)Avoiding function call in for loop
Normal Code:
Optimized Code:
(What?? about 4 times faster!! )
1.7. range() -> xrange()
It is implemented in Pure C.