Alternatively, how much worse are the others compared to local variables?
What's the big deal?
Some articles advise python programmers to use local variables if they will be used a lot, even if only referenced but not changed.
For example, here are two quotes from "Making Python Programs Blazing Fast" :
"There's actually difference in speed of lookup even between - let's say - local variable in function (fastest), class-level attribute (e.g. self.name - slower) and global for example imported function like time.time (slowest)."
"Don't Access Attributes
Another thing that might slow down your programs is dot operator (.) which is used when accessing object attributes. This operator triggers dictionary lookup using getattribute, which creates extra overhead in your code. "
Also, these are not the only possibilities. What about differences among:
I tested by using all these in loops with 1,000,000 iterations, but minimal work per iteration inside them. The functions were all methods of a class, except for the function used to test function attributes for functions outside a class.
A typical function was of the form:
def testINSA(self): s=0 for i in range(10000000): s+=self.INSA # what is after the = differs in each function. return s
All the code is at the bottom of this post.
| | | | Relative | | Where | Time | Rate | Performance | | LV Local Variable | 1.92 | 0.5208 | 100% | | GV Global Variable | 1.99 | 0.5020 | 96% | | ISA Instance Slotted Attribute | 2.09 | 0.4789 | 92% | | CA Class Attribute | 3.12 | 0.3204 | 62% | | INSA Instance Non-Slotted Attribute | 3.28 | 0.3051 | 59% | | FA Function Attribute | 3.49 | 0.2865 | 55% | | MA Method Attribute | 6.29 | 0.1589 | 31% |
Explanation:
When comparing performance, always compare the (Achievements / Resource), such as Miles per Gallon, or Calculations per Second, rather than Liters per Km, or Seconds per Calculation.
Yes, the local variables are the fastest.
The performance of the different types of variables clustered into three groupings.
The surprise is that compared to common wisdom, globals are second best, better even than slotted instance attributes in a class. Another surprise is that method attributes are the worst.
def testINSA(self): s=0 for i in range(10000000): s+=self.INSA # what is after the = differs in each function. return s
The above is the detailed content of How much better are python local variables over globals, attributes, or slots?. For more information, please follow other related articles on the PHP Chinese website!