Skip to content

TypedDict instead of dataclass? #6

Description

@nsmith-

In a microbenchmark it is slightly faster to use typed dictionaries:

import timeit
from dataclasses import dataclass
from typing import TypedDict


@dataclass
class TestClass:
    a: int
    b: bytes
    c: int


@dataclass
class TestDerived(TestClass):
    d: int
    e: bytes
    f: int


class TestClass2(TypedDict):
    a: int
    b: bytes
    c: int


class TestDerived2(TestClass2):
    d: int
    e: bytes
    f: int


ARGS = (1, b"2", 3, 4, b"5", 6)
KWARGS = {"a": 1, "b": b"2", "c": 3, "d": 4, "e": b"5", "f": 6}


@timeit.timeit
def make_from_args():
    return TestDerived(*ARGS)


@timeit.timeit
def make_from_dict():
    return TestDerived(**KWARGS)


@timeit.timeit
def make_from_dict_typed():
    return TestDerived2(KWARGS)  # type: ignore[call-arg]


if __name__ == "__main__":
    print("From args (us):", make_from_args)
    print("From dict (us):", make_from_dict)
    print("From typed dict (us):", make_from_dict_typed)

returns for me

From args (us): 0.09821387499687262
From dict (us): 0.1693307499808725
From typed dict (us): 0.06846924999263138

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions