哪个是最佳实践?冗余循环,还是在语句中调用相同的循环?
我正在学习如何编写最佳和最可读的代码。我写这本书的第一种方式具有冗余的陆面,但仅检查一次驱逐政策。虽然我的第二种方式没有循环的冗余,但请检查每次迭代的驱逐政策。有没有更好的方法来编写此代码?
if self.remainingSpace - content.size < 0:
if evictionPolicy == 'lru':
while self.remainingSpace - content.size < 0:
self.lruEvict()
else:
while self.remainingSpace - content.size < 0:
self.mruEvict()
或者
if self.remainingSpace - content.size < 0:
while self.remainingSpace - content.size < 0:
if evictionPolicy == 'lru':
self.lruEvict()
else:
self.mruEvict()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单,最快的版本。由于
emectionPolicy
永远不会更改,因此请先选择方法,以通用名称放置,然后使用单个公共循环:无代码加倍,无运行时重复检查调用每个循环的方法。
Simplest and fastest version. Since
evictionPolicy
never changes, select the method up front, put it in a common name, then use a single common loop:No doubling of code, no runtime repeated checks for which method to call on each loop.
正如 @Olivier-Melançon所述,如果 循环仅在这种情况下,您就不需要第一个
,因为
循环仅进入。第一个版本更有效,但是如果
self.lruevict()
或self.mruevict()
很昂贵,那么节省效率的节省可能会忽略不计:第二个是更多可读性IMO:
另一个选项,它将与第二个选项具有相同的效率,更简洁,但也许更晦涩:
当您使用
thing_if_true时,如果条件else thite thing_if_false
python中的ternary ocerator,thing_if_true
仅在条件
是真实的情况下才能计算或运行。编辑:通过交换
content.size
删除-
运算符到&lt;
的右侧,因为如果我们是微观优化,它使用不必要的开销,此外,代码看起来更好。As @olivier-melançon mentioned, you don't need the first
if
statmement, since thewhile
loop only enters in that case anyway.The first version is more efficient, but if either
self.lruEvict()
orself.mruEvict()
are expensive, then the efficiency savings may be negligible:The second is more readable IMO:
Another option which would be the same efficiency as the second option, more concise, but perhaps a bit more obscure:
When you use the
thing_if_true if condition else thing_if_false
ternary operator in Python, thething_if_true
only gets calculated or run ifcondition
is truthy, andthing_if_false
only gets calculated or run ifcondition
is falsey.Edit: Removed the
-
operator by swappingcontent.size
to the right side of the<
, since if we're micro-optimizing, it uses unnecessary overhead, and moreover the code looks nicer w/o it.