Reputation: 191
It may seem like an offtopic question, but I'm wondering about the right way (or better to say efficient way) to programme.
Let's say we have a web application and inside a function we have to check that a dictionary key has a certain value (or it can be applied to any object attribute check). Which of these ways are more efficient (in memory or speed) and why? Or if this is a wrong way to do that, why?
if myDictionary.get("xy") == "defined value":
runSomeFunction(myDictionary.get("xy"))
or
myVar = myDictonary.get("xy", "")
if myVar == "defined value":
runSomeFunction(myVar)
There may be a more diverse discussion in the ways we approach this code - in the web application (with hundreds of requests per minute) or in a normal script as a optimal way of programming.
Thanks in advance for any opinion.
Upvotes: 0
Views: 113
Reputation: 304
I'm not sure why you use the get()
method of the dict. This method should be used in cases where you don't know if a key exists – you didn't mention that to be the case. So I'm wondering why you don't just do:
if myDictionary["xy"] == "defined value":
...
A note to style: Typically CamelCasing is only used for class names; more Pythonic names would be my_dictionary
and run_some_function
.
A dictionary look-up is fast. Be sure that this is indeed a bottleneck by benchmarking your application – without knowing your code, I'm almost certain it is not. Python internally uses dictionaries for almost everything, it is unlikely that this particular dictionary access causes you performance problems.
Upvotes: 1
Reputation: 318518
If this kind of micro-optimization is relevant, using a scripting language is the wrong choice of technology. So the only proper answer besides the common "benchmark it" is: It does not really matter. Keep the code readable.
More technical explanation: dict
is implemented using a hash map, i.e. it has O(1)
lookup. So accessing an element is very fast. My guess would be that the temporary variable is a little bit faster since it does not involve calculating the hash of the key twice.
A timeit
benchmark with 1 million iterations shows the following times:
So using the temporary variable is actually a little bit slower. But note that this was for 1M iterations. So the actual average difference each time was just 0.00000002 seconds. That's nothing and just proves my initial point: Don't micro-optimize things that do not need to be optimized. Keep your code readable instead.
Upvotes: 4