开发者

Python: Does one of these examples waste more memory?

In a Django view function which uses manual transaction committing, I have:

context = RequestContext(request, data)
transaction.commit()
return render_to_response('basic.html', data, context)  # Returns a Django ``HttpResponse`` object which is similar to a dictionary.

I think it is a better idea to do this:

context = RequestContext(request, data)
response = render_to_response('basic.html', data, context)
transaction.commit()
return response

If the page isn't rendered correctly in the second version, the transaction is rolled back. This seems like the logical way of doing it albeit there won't likely be many exceptions at that point in the function when the application is in production.

But... I fear t开发者_Python百科hat this might cost more and this will be replete through a number of functions since the application is heavy with custom transaction handling, so now is the time to figure out.

If the HttpResponse instance is in memory already (at the point of render_to_response()), then what does another reference cost? When the function ends, doesn't the reference (response variable) go away so that when Django is done converting the HttpResponse into a string for output Python can immediately garbage collect it?

Is there any reason I would want to use the first version (other than "It's 1 less line of code.")?


You say, "there won't likely be many exceptions at that point in the function". This may not be true. Keep in mind that querysets are lazily fetched from the db, so in fact, a lot of your db activity could be inside the render_to_response call.

I'd use the second style. It's more correct in the sense that if something goes wrong in render_to_response, you want the transaction rolled back.

References cost almost nothing. Don't try to optimize them. Correctness is more important than absolute minimum memory footprint.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜