String Concatenation Performance Comparison: = vs. ''.join()
While addressing this topic in a previous answer, I became curious about the performance disparity between the = operator and the ''.join() method for string concatenation. Therefore, I decided to conduct a direct comparison.
According to the results of Efficient String Concatenation, ''.join() is far superior to the = operator in terms of speed. This discrepancy can be attributed to the immutable nature of strings in Python. As strings cannot be modified in place, any attempt to concatenate them requires the creation of a new string, which involves a significant computational overhead.
The following code snippets illustrate the performance difference:
<code class="python">def method1(): out_str = '' for num in xrange(loop_count): out_str += 'num' return out_str def method4(): str_list = [] for num in xrange(loop_count): str_list.append('num') return ''.join(str_list)</code>
While these methods are not entirely equivalent (method 4 appends to a list prior to joining the elements), they provide a reasonably accurate representation of the performance difference.
Visualizing the results, it becomes evident that string joining is significantly faster than concatenation:
[Image of test_20k.gif]
The above is the detailed content of Python String Concatenation: When is \'\'.join() Faster than =?. For more information, please follow other related articles on the PHP Chinese website!