python 如何处理条件语句中的临时变量?
How does python handle the temporary variables in a conditional statement?
假设我有以下代码
def vc_count(word, low, high):
if low > high:
return 0, 0
v, c = vc_count(word, low+1, high)
if word[low] in "aeiouAEIOU":
return v+1, c
else:
return v, c+1
def vc_count(word, low, high):
if low > high:
return 0, 0
v, c = vc_count(word, low+1, high)
vowels = "aeiouAEIOU"
if word[low] in vowels:
return v+1, c
else:
return v, c+1
在第二个版本中创建了一个名为 'vowels' 的字符串对象,而我在第一个版本中只写了 "aeiouAEIOU"。
这两者之间是否存在运行时差异或 space 使用差异?
另外,第一个版本的调用堆栈中会出现一个临时变量吗?如果不是,python是不是在in操作完成后直接丢弃?
不考虑其余的评论,运行 时间的表现并不显着。如果你确实想检查它,你可以使用 timeit
模块来查看所提供的两个版本的代码之间的差异,它应该是相当微小的差异。
但是要回答你的问题,是的,只要访问和使用堆栈(内存)中引用的那个变量,它就基本上被销毁了。但是,我更喜欢第一个版本 'better',因为它可以防止在实际应表示的变量中产生歧义。有时变量存储会被客户端覆盖而您可能不知道,这可能会导致函数出现您不希望发生的未定义行为。
假设我有以下代码
def vc_count(word, low, high):
if low > high:
return 0, 0
v, c = vc_count(word, low+1, high)
if word[low] in "aeiouAEIOU":
return v+1, c
else:
return v, c+1
def vc_count(word, low, high):
if low > high:
return 0, 0
v, c = vc_count(word, low+1, high)
vowels = "aeiouAEIOU"
if word[low] in vowels:
return v+1, c
else:
return v, c+1
在第二个版本中创建了一个名为 'vowels' 的字符串对象,而我在第一个版本中只写了 "aeiouAEIOU"。
这两者之间是否存在运行时差异或 space 使用差异?
另外,第一个版本的调用堆栈中会出现一个临时变量吗?如果不是,python是不是在in操作完成后直接丢弃?
不考虑其余的评论,运行 时间的表现并不显着。如果你确实想检查它,你可以使用 timeit
模块来查看所提供的两个版本的代码之间的差异,它应该是相当微小的差异。
但是要回答你的问题,是的,只要访问和使用堆栈(内存)中引用的那个变量,它就基本上被销毁了。但是,我更喜欢第一个版本 'better',因为它可以防止在实际应表示的变量中产生歧义。有时变量存储会被客户端覆盖而您可能不知道,这可能会导致函数出现您不希望发生的未定义行为。