
11.05.13 13:00, Stefan Behnel написав(ла):
Plus, such an optimisation can have a downside. Contrived example:
if DEBUG: print('a'.replace('a', 'aaaaaaaa').replace('a', 'aaaaaaaa') .replace('a', 'aaaaaaaa').replace('a', 'aaaaaaaa') .replace('a', 'aaaaaaaa').replace('a', 'aaaaaaaa'))
Expanding this into a string literal will trade space for time, whereas the original code clearly trades time for space. The same applies to string splitting. A list of many short strings takes up more space than a split call on one large string.
May not seem like a major concern in most cases that involve string literals, but we shouldn't ignore the possibility that the author of the code might have used the explicit method call quite deliberately.
x = 0 if x: x = 9**9**9