harshil21 · GitHub

Python's getattr is slow and should be avoided if we can directly access the attribute. Running this benchmark against master showed a ~15% performance gain on average:

import timeit
setup = """
from telegram import Message, User, Chat

user = User(id=123, first_name="John", is_bot=False)
chat = Chat(id=456, type="private")
"""
if __name__ == "__main__":
    direct_time = timeit.timeit(
        "Message(message_id=1, date=None, chat=chat, from_user=user, text='this', caption='wow', delete_chat_photo=True)",
        setup=setup,
        number=100000,
    )
    print(f"Direct instantiation time: {direct_time:.6f} seconds")    

Read the original on github.com ↗