Skip to content

Make instantiation of TelegramObjects 15% faster#5250

Open
harshil21 wants to merge 5 commits into
masterfrom
faster-setattr
Open

Make instantiation of TelegramObjects 15% faster#5250
harshil21 wants to merge 5 commits into
masterfrom
faster-setattr

Conversation

@harshil21
Copy link
Copy Markdown
Member

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")    

Benched on uv shipped Python 3.14.3, x86_64

@harshil21 harshil21 requested a review from aelkheir May 29, 2026 13:32
@harshil21 harshil21 added the 🔌 enhancement pr description: enhancement label May 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🔌 enhancement pr description: enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant