Skip to content

msgspec.structs.fields() is 20x slower than dataclasses.fields() #963

@kramar11

Description

@kramar11

Description

Hello, I noticed in a project where I have to frequently call msgspec.structs.fields that this method is compared to dataclasses extremely slow (about 20x slower).

from dataclasses import dataclass, fields
from timeit import timeit

import msgspec
msgspec_fields = msgspec.structs.fields


@dataclass
class D:
    x: int
    y: int | None = None
    z: str | None = None

class M(msgspec.Struct):
    x: int
    y: int | None = None
    z: str | None = None

d = D(1)
m = M(1)

print("dataclass.fields = ", end="")
print(timeit(lambda: fields(d), number=1000000))

print("msgspec.structs.fields = ", end="")
print(timeit(lambda: msgspec_fields(m), number=1000000))

Output:

dataclass.fields = 0.3529520556330681
msgspec.structs.fields = 7.523276620544493

Tested with python 3.13.7 and msgspec 0.19.0 and 0.20.0 (same result).

Maybe simply caching the data in a classvar is a fast solution here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions