封装严重损害性能? [英] Encapsulation severely hurts performance?

查看:61
本文介绍了封装严重损害性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题有点愚蠢,也许它只是编写代码的一部分,但似乎定义简单的函数确实会严重影响性能......我已经尝试过这个简单的测试:

I know this question is kind of stupid, maybe it's a just a part of writing code but it seems defining simple functions can really hurt performance severely... I've tried this simple test:

def make_legal_foo_string(x):
    return "This is a foo string: " + str(x)

def sum_up_to(x):
    return x*(x+1)/2

def foo(x):
    return [make_legal_foo_string(x),sum_up_to(x),x+1]

def bar(x):
    return ''.join([str(foo(x))," -- bar !! "])

它的风格非常好,使代码清晰,但它的速度可能是字面上写的三倍.对于可能有副作用的函数来说,这是不可避免的,但实际上定义一些函数几乎是微不足道的,这些函数每次出现时都应该用代码行替换,将源代码翻译成代码,然后才进行编译.同样我认为对于幻数,从内存中读取不需要很多时间,但是如果它们不应该被更改,那么为什么不在代码编译之前用文字替换每个magic"实例?

it's very good style and makes code clear but it can be three times as slow as just writing it literally. It's inescapable for functions that can have side effects but it's actually almost trivial to define some functions that just should literally be replaced with lines of code every time they appear, translate the source code into that and only then compile. Same I think for magic numbers, it doesn't take a lot of time to read from memory but if they're not supposed to be changed then why not just replace every instance of 'magic' with a literal before the code compiles?

推荐答案

函数调用开销不大;你通常不会注意到它们.您只能在这种情况下看到它们,因为您的实际代码 (x*x) 本身非常简单.在任何实际工作的实际程序中,花费在函数调用开销上的时间量都可以忽略不计.

Function call overheads are not big; you won't normally notice them. You only see them in this case because your actual code (x*x) is itself so completely trivial. In any real program that does real work, the amount of time spent in function-calling overhead will be negligably small.

(无论如何,我并不是真的建议在示例中使用 foo、identity 和 square;它们是如此微不足道,让它们内联同样具有可读性,并且它们并没有真正封装或抽象任何东西.)

(Not that I'd really recommend using foo, identity and square in the example, in any case; they're so trivial it's just as readable to have them inline and they don't really encapsulate or abstract anything.)

如果它们不应该被改变,那么为什么不在代码编译之前用文字替换每个 'magic' 实例?

if they're not supposed to be changed then why not just replace every instance of 'magic' with a literal before the code compiles?

因为程序的编写是为了让易于阅读和维护.您可以用它们的字面值替换常量,但这会使程序更难使用,因为它的好处非常小,您甚至可能永远无法测量它:高度过早优化.

Because programs are written for to be easy for you to read and maintain. You could replace constants with their literal values, but it'd make the program harder to work with, for a benefit that is so tiny you'll probably never even be able to measure it: the height of premature optimisation.

这篇关于封装严重损害性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆