Reputation:
I usually use "os.path.join()" when I connect path,I rarely use "os.sep". But I found "os.sep" is faster than "os.path.join()".Why?
My test code:
import os
import time
a = 'E:\\video'
b = 'image'
c = '0001.jpg'
start = time.clock()
d = os.path.join(a,b,c)
end = time.clock()
print("%f " % (end - start)) #0.000011
print(d) #E:\video\image\0001.jpg
start = time.clock()
e = a+os.sep+b+os.sep+c
end = time.clock()
print("%f " % (end - start)) #0.000001
print(e) #E:\video\image\0001.jpg
Result:
Upvotes: 2
Views: 2595
Reputation: 763
As per python official documentation for os.path which says :
Since different operating systems have different path name conventions, there are several versions of this module in the standard library. The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths.
As we can see that it is suitable for os independent path name conventions, there must be additional checks which goes on, for say determining the OS etc, which are the reasons for the time required in os.path.join(a,b,c) call.
Also a+os.sep+b+os.sep+c is just a separator in simple terms which doesn't perform such operations as os.path.
Upvotes: 0
Reputation: 77912
You can answer this by yourself by reading the source (windows version) - or even just the doc FWIW:
Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.
As you can see, os.path.join()
does much more than mere string concatenation, so yes obviously it's slower.
Upvotes: 2