简体   繁体   English

在函数性能中声明元组

[英]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. 您可以使用dis模块反汇编功能字节码。 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. 您可以看到第二个版本的改进:不必每次调用都加载和存储tuple

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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