We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
In the first solution you're constantly creating new copies of the string. Because Python strings are immutable, when you do += you create a copy of the original string to add the extra character. Of course the interpreter could optimize this by realizing you're not referring to the old string anymore and avoiding the entire copy but you're relying on an optimization.
In the second one you are upfront telling the interpreter exactly how many characters it needs to allocate for the joined string, so it can do it all in one go instead of creating copies. The implementation of join would NOT be as follows as that would run into the same issue:
defjoin(delim,toks):ret=""fortokintoks:s+=tok+delim# yes this impl will add an extra tok at the endreturnret
Hash Tables: Ransom Note
You are viewing a single comment's thread. Return to all comments →
In the first solution you're constantly creating new copies of the string. Because Python strings are immutable, when you do += you create a copy of the original string to add the extra character. Of course the interpreter could optimize this by realizing you're not referring to the old string anymore and avoiding the entire copy but you're relying on an optimization.
In the second one you are upfront telling the interpreter exactly how many characters it needs to allocate for the joined string, so it can do it all in one go instead of creating copies. The implementation of join would NOT be as follows as that would run into the same issue: