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, 2019 in Python by ana1504.k
• 7,910 points
1,994 views

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, 2019 by SDeb
• 13,300 points

Related Questions In Python

+1 vote
1 answer
+1 vote
2 answers

Replace every character of string by character whose ASCII value is K times more than it

Refer below code for your problem statement def ...READ MORE

answered May 17, 2020 in Python by Kumar Sambhawam

edited May 18, 2020 by Gitika 17,378 views
0 votes
1 answer

String is immutable data type. String.replace() So why there is command for string to replace the values....??

Hey, @Nelson, replace() actually returns a *copy* of ...READ MORE

answered Mar 30, 2020 in Python by Gitika
• 65,770 points
5,771 views
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
692 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,468 views
0 votes
1 answer
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, 2019 in Python by SDeb
• 13,300 points
1,083 views
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,300 points
754 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP