简体   繁体   English

全局变量 vs getter 函数 vs 函数变量

[英]global variable vs getter functions vs function variable

I have a scenario that can be implemented in multiple ways.我有一个可以通过多种方式实现的场景。 I need suggestion which is more optimized / python way of implementing and why ?我需要更优化/python 实现方式的建议,为什么?

lets consider nested function calls as funca1 -> funca2 -> funca3 ->funca4 funcb1 -> funcb2 -> funcb3 ->funcb4让我们将嵌套函数调用视为 funca1 -> funca2 -> funca3 ->funca4 funcb1 -> funcb2 -> funcb3 ->funcb4

if __name__ == "__main__":
    funca1()
    funcb1()

and varx variable is only used / or needed by funca4 and funcb3.并且 varx 变量仅被funca4和funcb3使用/或需要。 then we have below options那么我们有以下选项

  1. create varx as global variable and use it funca4 and funcb3 with out passing through all the functions创建 varx 作为全局变量并使用它 funca4 和 funcb3 而不传递所有函数
  2. pass the varx variable across all the functions even through its used only in two functions将 varx 变量传递到所有函数,即使它仅在两个函数中使用
  3. create another functions get_varx() function and only use this inside funca4, funcb4.创建另一个函数 get_varx() 函数并且只在 funca4、funcb4 中使用它。

This can also be achieved by creating class and assigning varx as property .这也可以通过创建类并将 varx 分配为 property 来实现。 But current design of the project doesn't allow this但目前的项目设计不允许这样做

I ran a demo code with the scenarios you gave, and timed the execution time using the time module and obtained the following results:我用你给出的场景运行了一个演示代码,并使用time模块对执行时间进行计时,并获得以下结果:

Fastest Execution Rankings:最快执行排名:

  1. Creating another function to get the value.创建另一个函数来获取值。
  2. Creating varx as a global variable.创建varx作为全局变量。
  3. Passing the varx variable accross all the functions.在所有函数中传递varx变量。

Optimization is relative.优化是相对的。

You can optimize by:-您可以通过以下方式优化:-

  1. your code to have less lines/characters你的代码有更少的行/字符

  2. you want minimum memory consumption你想要最小的内存消耗

  3. you want minimum time required.你想要最少的时间。

Minimum time would be another function method最短时间将是另一种函数方法

Minimum memory and minimum lines would be global variable.最小内存和最小行数将是全局变量。

Passing a variable through all is just unnecessary and duplicates the variables in each local scope consuming alot of memory hence this should be avoided.将变量传递给 all 是不必要的,并且会在每个本地作用域中复制变量,从而消耗大量内存,因此应该避免这种情况。

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

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