Hacker News new | ask | show | jobs
by jammycrisp 1797 days ago
Y'all may be interested in a fast dataclass-like library I maintain called msgspec (https://jcristharif.com/msgspec/) that provides many of the benefits of dataclasses (mutable, type declarations), but with speedy performance. The objects are mainly meant to be used for (de)serialization (currently only msgpack is supported, but JSON support is in the works), with native type validation (think a faster pydantic).

Mirroring the author's initialization benchmark:

    In [1]: import msgspec

    In [2]: from typing import NamedTuple

    In [3]: class Point(msgspec.Struct):
    ...:     x: int
    ...:     y: int
    ...: 

    In [4]: class PointNT(NamedTuple):
    ...:     x: int
    ...:     y: int
    ...: 

    In [5]: %timeit Point(1, 2)
    48.4 ns ± 0.195 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

    In [6]: %timeit PointNT(1, 2)
    185 ns ± 0.851 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
1 comments

Is this faster than Attrs as well?
Yes, but it's also less flexible. Tradeoffs.