Skip to content
Advertisement

Python string join performance

There are a lot of articles around the web concerning Python performance. The first thing you read is concatenating strings should not be done using ‘+’; avoid s1 + s2 + s3, and instead use str.join

I tried the following: concatenating two strings as part of a directory path: three approaches:

  1. ‘+’ which I should not do
  2. str.join
  3. os.path.join

Here is my code:

JavaScript

Here the results (Python 2.5 on Windows XP):

JavaScript

Shouldn’t it be exactly the other way around?

Advertisement

Answer

It is true you should not use ‘+’. Your example is quite special. Try the same code with:

JavaScript

Then the second version (str.join) is much faster.

Advertisement