[英]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
那么我们有以下选项
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:最快执行排名:
varx
as a global variable.varx
作为全局变量。varx
variable accross all the functions.varx
变量。Optimization is relative.优化是相对的。
You can optimize by:-您可以通过以下方式优化:-
your code to have less lines/characters你的代码有更少的行/字符
you want minimum memory consumption你想要最小的内存消耗
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.