开发者

Python "import" performance query

开发者 https://www.devze.com 2023-03-26 14:16 出处:网络
Well, this qu开发者_运维百科ery struck my mind when someone pointed out to me that importing a package using import package gives more code readability. Is this actually true? I mean when using this s

Well, this qu开发者_运维百科ery struck my mind when someone pointed out to me that importing a package using import package gives more code readability. Is this actually true? I mean when using this statement as compared to from package import x, y, z, isn't there any overhead of importing the entire package?


I don't expect any performance difference. Whole package will be loaded anyway.

For example:

# load dirname() function from os.path module
>>> from os.path import dirname

#the os.path.basename() was not imported
>>> basename('/foo/bar.txt')
NameError: name 'basename' is not defined

# however, basename() is already available anyway:
dirname.__globals__['basename']('/foo/bar.txt')


Using the point notation is always less performant than importing a function directly and calling it, because the function does have to be searched in the modules dictionary. This counts for every getattr operation.

For example when appending items to a list:

lst     = []
for i in xrange(5000):
    lst.append(i ** .5 * 2)

This is faster:

lst     = []
append  = lst.append
for i in xrange(5000):
    append(i ** .5 * 2)

This can make a real heavy difference.

>>> def bad():
...     lst     = []
...     for i in xrange(500):
...         lst.append(i ** .5 * 2)
>>> def good():
...     lst     = []
...     append  = lst.append
...     for i in xrange(500):
...         append(i ** .5 * 2)
>>> from timeit import timeit
>>> timeit("bad()", "from __main__ import bad", number = 1000)
0.175249130875
>>> timeit("good()", "from __main__ import good", number = 1000)
0.146750989286


The performance will be same either way. The entire module is compiled, if needed, and the code executed, the first time you import a module, no matter how you import it.


Which is more readable

from os.path import split, join

then a bunch of split and join calls that would accidentally be read as the string methods of the same name, or

import os.path

then referencing them as os.path.split and os.path.join? Here, it's clear they're methods dealing with paths.

Either way, you have to actually load the whole module. Otherwise, things that you imported that depended on other things in the module you didn't import wouldn't work.

0

精彩评论

暂无评论...
验证码 换一张
取 消