How Much Overhead Do Decorators Add To Python Function Calls
Solution 1:
The overhead added by using a decorator should be just one extra function call.
The work being done by the decorator isn't part of the overhead as your alternative is to add the equivalent code to the decorated object.
So it's possible that the decorate function takes twice as long to run, but that's because the decorator is doing some important work that takes roughly the same time to fun as the undecorated function.
Solution 2:
What is important to know is that a decorator has a simple effect:
@decoratordeff():
…
is just syntactic sugar for
def f():
…
f =decorator(f)
Thus, if decorator does not do anything, you do not have any overhead when calling the decorated function (the call decorator(f)
does take a little time, though), like in
decorator = lambdafunc: func
@decoratordeff():
…
If the decorator does anything, you only get whatever time overhead the decorator involves. This typically include an additional function call (that of the decorated function), as in
defdecorator(func):
defdecorated_func():
print"Before calling function", func # Some overhead (but that's normal)
func() # This will be a second function call, after the call to decorated_func()return decorated_func
Thus, in itself, decorating a function does not add much overhead for what you want to do: the only obvious overhead that you could in principle remove would be to not call func()
in the decorated function but instead copy its full code, but the legibility of the code would suffer (legibility and flexibility are some of the reasons decorators do exist in the first place).
Solution 3:
Do decorators add significant overhead to a system? I can't find anything to back that up.
They add almost no measurable overhead. Zero.
It's important to note that the decorator runs once to create the decorated function. Once.
The decorated function has two parts to it.
whatever decoration was added. This is not overhead.
plus the original function. This is not overhead.
There's no real overhead at all. You might -- with some care -- be able to measure the overhead of one extra function call-and-return as part of a decorated function, but that's almost unmeasurably small. And it's probably far less than an alternative design that doesn't use decoration.
Post a Comment for "How Much Overhead Do Decorators Add To Python Function Calls"