0

So I recently read an article online about optimizing Python, and it said that concatenating strings with .join()

concatenatedString = " ".join (["Hello", "world!"])

is quicker than with the + operator

concatenatedString = "Hello " + "world!"

I tried both of them on a python debugger, and I found that using .join() is indeed quicker than using the + operator.

Why is this?

philipxy
  • 14,867
  • 6
  • 39
  • 83
Lunar
  • 108
  • 8
  • It helps, but the answer is slightly different, as it is with the += operator – Lunar Aug 08 '21 at 17:41
  • Added some additional prior instances of this question to the duplicate list. BTW, note that this is very old advice, and concatenating strings with `+` is not nearly as slow with Python-of-today as it was 15 years ago. Not that `join()` isn't faster, but it's not _as much_ faster as it used to be. Keep an eye on the vintage of what you read on the topic. – Charles Duffy Aug 08 '21 at 17:47
  • 1
    (Mind, "why" questions are somewhat questionable to the extent that they go beyond asking what _is best_, into asking _why_ that thing is best; our scope is narrowly focused on "_practical_, answerable questions"; if you already know that X is the right way to do something, and knowing _why_ it's the best way won't change how you write code, it doesn't change how you go about the practice of software development, and is therefore not a practical question). – Charles Duffy Aug 08 '21 at 17:54

0 Answers0