开发者

Django: is importing a view from a module slower than including it in the main views.py file?

This may be more of a question about how Python itself imports methods, which while I understand on a surface level, I don't really have a deep understanding of.

An extremely simplified example might make things clearer. Of the two examples below, would there be any noticeable difference in speed of execution?

Example 1

# views.py

from app_name.models import *

def add_item(request, name,开发者_如何学JAVA category):
    item = Item(name=name, category=category)
    item.save()
    return HttpResponseRedirect('/')

Example 2

# views.py

from app_name.models import *
from app_name.items import add_new_item

def add_item(request, name, category):
    item = add_new_item(request, name, category)
    return HttpResponseRedirect('/')

# items.py

def add_new_item(request, name, category):
    item = Item(name=name, category=category)
    item.save()
    return item

I should add again that this is an extremely simplified example, and is not reflective of an actual real world decision. I am just interested in understanding how Python works and if Example 2 would be noticeably slower, and if so under what circumstances.

Thanks.


You won't see any difference in speed. Once a module is imported, it is kept in memory so it doesn't have to be loaded again. You can check what has been loaded like so:

import sys
print sys.modules
# {'cStringIO': <module 'cStringIO' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/cStringIO.so'>, 'copy_reg': <mo........


The very act of importing something "slows" the application down. However, we're talking about the time it takes to read the file from the filesystem and compile it once -- milliseconds. So, yes, importing the view versus the view just being there is slower, but practically, there's no difference.


As the others have already pointed out your examples won't make any difference as the import will only happen once. More important is, that you should make sure not to do eg. any imports inside a function if it that is avoidable, as, these imports will be redone every time the function is executed!

If you want to have clear and maintable code, it is far more important to take care of the structuring of your imports and, a wildcard import like from app_name.models import * is pretty evil, you should avoid it! See also eg. this post!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜