Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Makeemail.message.Message.__contains__ faster #100792

Closed
Assignees
sobolevn
Labels
@sobolevn

Description

@sobolevn

Right now the implementation ofMessage.__contains__ looks like this:

def__contains__(self,name):
returnname.lower()in [k.lower()fork,vinself._headers]

There are several problems here:

  1. We build intermediate structure (list in this case)
  2. We uselist forin operation, which is slow

The fastest way to do check if actually have this item is simply by:

def__contains__(self,name):name_lower=name.lower()fork,vinself._headers:ifname_lower==k.lower():returnTruereturnFalse

We do not create any intermediate lists / sets. And we even don't iterate longer than needed.
This change makesin check twice as fast.

Microbenchmark

Before

» pyperf timeit --setup 'import email; m = email.message_from_file(open("Lib/test/test_email/data/msg_01.txt"))' '"from" in m'.....................Mean +- std dev: 1.40 us +- 0.14 us
pyperf timeit --setup 'import email; m = email.message_from_file(open("Lib/test/test_email/data/msg_01.txt"))' '"missing" in m'.....................Mean +- std dev: 1.42 us +- 0.06 us

After

» pyperf timeit --setup 'import email; m = email.message_from_file(open("Lib/test/test_email/data/msg_01.txt"))' '"missing" in m'.....................Mean +- std dev: 904 ns +- 55 ns
» pyperf timeit --setup 'import email; m = email.message_from_file(open("Lib/test/test_email/data/msg_01.txt"))' '"from" in m'.....................Mean +- std dev: 715 ns +- 24 ns

The second case is now twice as fast.
It probably also consumes less memory now, but I don't think it is very significant.

Importance

SinceEmailMessage (a subclass ofMessage) is quite widely used by users and 3rd party libs, I think it is important to be included.

And since the patch is quite simple and pure-python, I think the risks are very low.

Linked PRs

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions


    [8]ページ先頭

    ©2009-2025 Movatter.jp