Replace with list.append() and then ‘’.join(list) (O(N) instead of O(N^2))
Alternatively:
list comprehension, generator expression, map, itertools, array.array(‘u’), bytearray, io.TextIO, io.BytesIO or writelines() the list to file, or directly write() strings to file.
Also f’’ 2x faster format() 2x faster str + str
Check for global variables
Replace with local ones, which are faster, also hoist attribute lookups outside of loops (if method doesn’t change object), by assigning to variable for speed improvement (modest speed improvement also for builtins when assigned to local namespace).
Replace loops
Use list comprehensions, generator expressions, map and filter (only with builtins, not lambda) instead.
Check for string concatenation
Replace with
list.append()
and then‘’.join(list)
(O(N) instead of O(N^2)) Alternatively: list comprehension, generator expression,map
,itertools
,array.array(‘u’)
,bytearray
,io.TextIO
,io.BytesIO
orwritelines()
the list to file, or directlywrite()
strings to file. Alsof’’
2x fasterformat()
2x fasterstr + str
Check for global variables
Replace with local ones, which are faster, also hoist attribute lookups outside of loops (if method doesn’t change object), by assigning to variable for speed improvement (modest speed improvement also for builtins when assigned to local namespace).
Replace loops
Use list comprehensions, generator expressions, map and filter (only with builtins, not lambda) instead.