Why are Lists faster than character arrays for string concatenation?

0 votes
Why does method 3 (Mutable Character Arrays) result in a significantly slower performance than method 4 (joining a list of strings)?

As far as I know, both of them are mutable and I would think that they should have comparable performance.
Jun 12 in Python by ana1504.k
• 7,870 points

1 answer to this question.

0 votes

It's true that in the list-append method, the list is mutable. But building up the list isn't the slow part. If you have 1000 strings of average length 1000, you're doing 1000000 mutations to the array, but only 1000 mutations to the list (plus 1000 increfs to string objects).

In particular, that means the array will have to spend 1000x as much time expanding (allocating new storage and copying the whole thing so far).

The slow part for the list method is the str.join call at the end. But that isn't mutable, and doesn't require any expanding. It uses two passes, to first calculate the size needed, then copy everything into it.

answered Jun 12 by SDeb
• 13,160 points

Related Questions In Python

0 votes
1 answer

Slice notation in Python for string reversal

The slice notation is [start:end:step]. Step = ...READ MORE

answered Apr 25, 2018 in Python by Nietzsche's daemon
• 4,260 points
0 votes
1 answer

Why is openpyxl is required for loading excel format files?

Well, it sounds like openpyxl is not ...READ MORE

answered Aug 8, 2018 in Python by Priyaj
• 56,900 points
0 votes
1 answer

Python join: why is it string.join(list) instead of list.join(string)?

950down voteaccepted It's because any iterable can be ...READ MORE

answered May 15, 2018 in Python by ariaholic
• 7,340 points
0 votes
2 answers

Finding the index of a character in python string

You can use word.find('o') as well to ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 283 views
0 votes
1 answer

Why do variables have bigger scopes in Python than in C?

Only functions, modules, and the bodies of ...READ MORE

answered Jul 2 in Python by SDeb
• 13,160 points
0 votes
1 answer

What are the ternary conditional operator in Python?

The Ternary Conditional operator was added in ...READ MORE

answered Sep 19, 2018 in Python by SDeb
• 13,160 points