jsstuball
jsstuball

Reputation: 4931

Overhead on get_event_loop() call

I am debating whether to include the line loop = asyncio.get_event_loop() once per file or to write loop = asyncio.get_event_loop() every time I need a handle on the event loop, so several times throughout the file inside various methods which need to create tasks.

My colleague is arguing that having globals outside of classes is poor style. But I am not delighted about wasting CPU cycles with the, however small, overhead on this get_event_loop method as well as simply the extra line of code in each method.

Which is the better way?

Upvotes: 1

Views: 332

Answers (2)

Andrew Svetlov
Andrew Svetlov

Reputation: 17376

In Python 3.7 the amortized time of get_event_loop() call if barely comparable with a time of C function call and much faster than Python function call time.

For Python 3.6 the function is a little slower but still is not a bottleneck for any user code I bet.

Upvotes: 3

user4815162342
user4815162342

Reputation: 155046

Unless you can actually prove that the overhead of get_event_loop is making a negative impact on your application, I would advise against making that microoptimization. Using get_event_loop ensures that your code will run under multiple event loops, which are regularly created by test harnesses or by multiple invocations of asyncio.run.

If you absolutely feel you must optimize away the call to get_event_loop, at least make a class and store it in the instance during construction. That way you get the benefit of avoiding a function call, while your code remains runnable under multiple event loops, at least as long as your objects are designed not to outlive the event loop.

Upvotes: 3

Related Questions