Skip to content

Make instantiation of TelegramObjects 15% faster#5250

Merged
harshil21 merged 5 commits into
masterfrom
faster-setattr
May 31, 2026
Merged

Make instantiation of TelegramObjects 15% faster#5250
harshil21 merged 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
Copy link
Copy Markdown
Member

@aelkheir aelkheir left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice I could get similar numbers

(venv) ➜  python-telegram-bot git:(master) ✗ python bench.py
Direct instantiation time: 2.532094 seconds
(venv) ➜  python-telegram-bot git:(master) ✗ python bench.py
Direct instantiation time: 2.728747 seconds
(venv) ➜  python-telegram-bot git:(master) ✗ python bench.py
Direct instantiation time: 2.742132 seconds
(venv) ➜  python-telegram-bot git:(master) ✗ python bench.py
Direct instantiation time: 2.695864 seconds
# --------
(venv) ➜  python-telegram-bot git:(faster-setattr) ✗ python bench.py
Direct instantiation time: 2.403684 seconds
(venv) ➜  python-telegram-bot git:(faster-setattr) ✗ python bench.py
Direct instantiation time: 2.351534 seconds
(venv) ➜  python-telegram-bot git:(faster-setattr) ✗ python bench.py
Direct instantiation time: 2.347846 seconds
(venv) ➜  python-telegram-bot git:(faster-setattr) ✗ python bench.py
Direct instantiation time: 2.326989 seconds
(venv) ➜  python-telegram-bot git:(faster-setattr) ✗

@harshil21 harshil21 merged commit 1f34359 into master May 31, 2026
26 of 30 checks passed
@harshil21 harshil21 deleted the faster-setattr branch May 31, 2026 16:47
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.

2 participants