Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAli Mammadov
2,172 PointsString concatenation performance in Python
Is there a more efficient, in terms of used resources, way to concatenate strings in Python?
2 Answers
Kenneth Love
Treehouse Guest TeacherAre you just trying to join a bunch of strings together? .join()
is probably faster & more memory efficient than +
.
That said, string concatenation in Python isn't very inefficient since the GC is pretty solid.
Vittorio Somaschini
33,371 PointsHello Ali.
I think that is the way to do concatenation in Python, but in the following videos you will discover a way to put variables inside strings using placeholders and .format().
I am pretty sure you will like it!
;)
Ali Mammadov
2,172 PointsBut string concatenation eats a lot of memory, because it creates useless duplicates of strings in RAM. How can I get rid of this? I'm trying to concatenate pretty big strings (>500 characters each).
Ali Mammadov
2,172 PointsAli Mammadov
2,172 PointsAre there any alternatives to
.join()
?Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherNot really. You could do it the slower and concatenation way.
Are you really in a position where you need to optimize this? If you're not, don't waste time on it.
Ali Mammadov
2,172 PointsAli Mammadov
2,172 PointsBelieve me, I am! I have came to a few versions. How do you think, which of them will be the fastest?
cdmp = "%(BIN)s%(CC)s%(EXP)s%(HLDR)s" % locals()
cdmp = "{BIN}{CC}{EXP}{HLDR}".format(**locals())