views:

108

answers:

3

I am wondering would this make any real efficieny difference (ie computation time, memory etc..)

This is my model:

class FooUser(models.Model):
    name = models.CharField(max_length=50)
    sirname = models.CharField(max_length=50)

Assume I have 2 different approaches while saving a FooUser at a view: First one, assigning retrieved values to a variable and pass it to the object after that.

#say I retrieve name and sirname from users cookie.(lets not care for the exceptions for now.
input_name =request.session['name']
input_sirname =request.session['sirname']

FooUser(name=input_name,sirname=input_sirname).save()

Second one, directly passing as parameter:

#say I retrieve name and sirname from users cookie.(lets not care for the exceptions for now.
FooUser(name=request.session['name'],sirname=request.session['sirname']).save()

I know this question can be a little stupid but for long inputs, passing these inputs to the object makes the code almost unreadable :)

+3  A: 

This:

 input_name =request.session['name']
 input_sirname =request.session['sirname']

is not copying strings to variables. It's only assigning pointers to string objects to names in local dictionary (input_name, input_sirname). For better explanation you can take a loot at this: http://effbot.org/zone/python-objects.htm.

Writing this, having those intermediate dictionary entries (input_name, input_sirname) has such low overhead in 99,999% of cases, that I bet you have some other bottlenecks in your program you should focus on.

And remember: premature optimization is the root of all evil :-)

Tomasz Zielinski
+1 for the premature optimization reminder.
celopes
A: 

I would argue that the second method (with passing request.session elements directly) is more readable. Looking at the code I know immediately what's going on - it's creating an object using raw, unmodified session data. Had it been just a variable I wouldn't know where it comes from, had it been modified in the meantime etc. I would have to read much larger portion of the code. You can split the statement over multiple lines.

FooUser(
    name=request.session['name'],
    sirname=request.session['sirname']
).save()
Ludwik Trammer
+1  A: 

The time required to bind a local name to a value, as in, e.g., input_name = request.session['name'], is absolutely negligible compared to the time executing .save() itself will take -- you'll never be able to measure it. So, forget such small efficiencies and focus on style, robustness, maintainability (which are fine in both cases in your example) -- if and when you need to tune your application for speed, start by profiling it.

Alex Martelli