简体   繁体   中英

Declare tuple inside a function performance

Should i declare a tuple inside function or globally? If inside, will it be recreate on every function call?

def isBracket(s):
    t = ('a','b','c','d')
    return s in t

You can use the dis module to disassemble the function bytecode. You will see the difference:

>>> import dis
>>> def isBracket(s):
...     t = ('a','b','c','d')
...     return s in t
... 
>>> dis.dis(isBracket)
  2           0 LOAD_CONST               5 (('a', 'b', 'c', 'd'))
              3 STORE_FAST               1 (t)

  3           6 LOAD_FAST                0 (s)
              9 LOAD_FAST                1 (t)
             12 COMPARE_OP               6 (in)
             15 RETURN_VALUE        
>>> t = ('a','b','c','d')
>>> def isBracket(s):
...     return s in t
... 
>>> dis.dis(isBracket)
  2           0 LOAD_FAST                0 (s)
              3 LOAD_GLOBAL              0 (t)
              6 COMPARE_OP               6 (in)
              9 RETURN_VALUE

You can see the improvement of the second version: The tuple does not have to be loaded and stored every call.

If it is a tuple of constant values, there is nothing wrong with putting outside of the function, because otherwise it will created every time the function is called.

In order to keep the mental scope of this constant close to code it is used in, put it right above your function definition.

t = ('a','b','c','d')

def isBracket(s):
    return s in t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM