Does encapsulation severely degrade performance?

I know this question is stupid, maybe it’s just part of writing code, but it seems that defining simple functions can seriously hurt performance ... I 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 !! "])

it is very good style and makes the code understandable, but it can be three times slower than just writing it literally. This is inevitable for functions that can have side effects, but it’s actually almost trivial to define some functions that literally need to be replaced with lines of code every time they appear, translate the source code into this and only then compile it. I think the same thing with magic numbers, it does not take long to read from memory, but if they should not change, then why not just replace each instance of β€œmagic” with a literal before compiling the code?

+3
source share
8 answers

; . , (x * x) . , , , , .

( , foo, identity square , , , , , -).

, "" ?

, . , , : .

+6

, python , , //, . , , "-" .

+2

- : . , , .

. : , , , . , ?

def DamagePlayer(dmg):
    player.health -= dmg;

, "player.health - =" . , powerup, , ? , :

def DamagePlayer(dmg):
    if player.hasCoolPowerUp:
        player.health -= dmg / 2
    else
        player.health -= dmg

, - . 50 , , , : " , , , AlienSheep..."

Alien Sheep? .:)

, , , , - . , , . , , ( ), . - . , . .

+2

.

, , Python, . :

  • Java getter & setter - , JIT getters & configureers.

  • , , . ...

+1

, , - - . (, , ).

- , ? , , . ? , . 'foo' , , , :

''.join(foo(x)," -- bar !! "])

, , .

, . , , .

0

IMO, . , . . , .

, . ., , ++ FQA Lite ( " , , , " ). ++. /, .

, :

$ python bench.py 
fine-grained function decomposition: 5.46632194519
one-liner: 4.46827578545
$ python --version
Python 2.5.2

, . . bench.py ​​ pastebin.

0

, , . , , , , .

, inlining, , .

Python . , , .

, , ( , , ), , python , .

0

, , , . Python , , ; . Python, .

, :

# beginning of the file xxx.py
log = lambda *x: None 

def something():
    ...
    log(...)
    ...

( log ), - :

import xxx
xxx.log = print
xxx.something()

, log --- - . , log .

Similarly, if an exception were to occur in make_legal_foo_string(this is possible, for example, if it is x.__str__()broken and returns None), you will get to the original quote from the wrong line and even, possibly, the wrong file in your script.

There are some tools that actually apply some optimizations for Python code, but I don't think about what you suggested.

0
source

Source: https://habr.com/ru/post/1716604/


All Articles