Retronix
Retronix

Reputation: 226

Do function declarations in the middle of a function slow down performance?

Example of what I'm asking about:

def foo(bar):
    """Do a print function bar times"""
    count = 0
    while count < bar:
        def baz():
            return "This is baz"
        print(baz())
        count += 1

Does the function declaration in the middle of the while loop slow down the execution time of foo?

Upvotes: 2

Views: 155

Answers (1)

Polkaguy6000
Polkaguy6000

Reputation: 1208

To expand on one of the comments, you are adding additional work to your loop. Every time you declare baz() the compile is doing work and allocating memory. Is there any particular reason you wanted to do it this way?

More efficient code:

def foo(bar):
    """Do a print function bar times"""
    count = 0
    def baz():
       return "This is baz"
    while count < bar:
        print(baz())
        count += 1

Most efficient code:

def baz():
    return "This is baz"
def foo(bar):
    """Do a print function bar times"""
    count = 0
    while count < bar:
        print(baz())
        count += 1

Upvotes: 2

Related Questions