0

I have few questions which are bothering me since few days back. I'm a beginner Python/Django Programmer so I just want to clear few things before I dive into real time product development.(for Python 2.7.*)

1) saving value in a variable before using in a function

for x in some_list/tuple:
    func(do_something(x))

for x in some_list/tuple:
    y = do_something(x)
    func(y)

Which one is faster or which one I SHOULD use.

2)Creating a new object of a model in Django

def myview(request):
    u = User(username="xyz12",city="TA",name="xyz",...)
    u.save()

def myview(request):
    d = {'username':"xyz12",'city':"TA",'name':"xyz",...}
    u = User(**d)
    u.save()

3) creating dictionary

var = Dict(key1=val1,key2=val2,...)
var = {'key1':val1,'key2':val2,...}

4) I know .append() is faster than += but what if I want to append a list's elements to another

a = [1,2,3,],b=[4,5,6]

a += b

or

for i in b:
  a.append(i)
Zulu
  • 8,765
  • 9
  • 49
  • 56
Eric
  • 21
  • 2
  • 3
    These are all fairly trivial issues and worrying about any performance considerations is likely misguided. Personally I prefer the first option in all but the 3rd example. – wim Jul 04 '14 at 19:02

1 Answers1

0

This is a very interesting question, but I think you don't ask it for the good reason. The performances gained by such optimisations are negligible, especially if you're working with small number of elements.

On the other hand, what is really important is the ease of reading the code and it's clarity.

def myview(request):
    d = {'username':"xyz12",'city':"TA",'name':"xyz",...}
    u = User(**d)
    u.save()

This code for example isn't "easy" to read and to understand at first sight. It requires to think about it before finding what is actually does. Unless you need the intermediary step, don't do it.

For the 4th point, I'd go for the first solution, way much clearer (and it avoids the function call overhead created by calling the same function in a loop). You could also use more specialised function for better performances such as reduce (see this answer : https://stackoverflow.com/a/11739570/3768672 and this thread as well : What is the fastest way to merge two lists in python?).

The 1st and 3rd points are usually up to what you prefer, as both are really similar and will probably be optimised when compiled to bytecode anyway.

If you really want to optimise more your code, I advise you to go check this out : https://wiki.python.org/moin/PythonSpeed/PerformanceTips

PS : Ultimately, you can still do your own tests. Write two functions doing the exact same things with the two different methods you want to test, measure the execution times of these methods and compare them (be careful, do the tests multiple time to reduce the uncertainties).

Community
  • 1
  • 1
Raphael Laurent
  • 1,941
  • 1
  • 17
  • 27