DEV Community

jneeee
jneeee

Posted on

Pydantic have very bad performance

I have compare it with dataclasses, Nametuple, msgspec.Struct

Pydantic is the heavest package but with badest performace. I do not understand why still so many people use it.

Here is my test code:

import time
import sys
from typing import NamedTuple
from dataclasses import dataclass

from msgspec import Struct
from pydantic import BaseModel

class PointNamedTuple(NamedTuple):
    x: int
    y: int

@dataclass
class PointDataClass:
    x: int
    y: int

@dataclass(slots=True)
class PointDataClassSlots:
    x: int
    y: int


class Pointbymsgspec(Struct):
    x: int
    y: int


class Pointbypydantic(BaseModel):
    x: int
    y: int


NUM_OBJECTS = 1_000_000


def test_create_instance(func, num_objects=NUM_OBJECTS):
    start = time.perf_counter()
    _list = [func(x=i, y=i) for i in range(num_objects)]
    _size = sys.getsizeof(_list[0])
    print(f"{func.__name__}: {time.perf_counter() - start:.5f}s, {_size/1024} Bit")
    return time.perf_counter() - start, _size

print(f"Create {NUM_OBJECTS} instance, funcs: time(s): size(Bit)")
test_create_instance(PointNamedTuple)
test_create_instance(PointDataClass)
test_create_instance(PointDataClassSlots)
test_create_instance(Pointbymsgspec)
test_create_instance(Pointbypydantic)
Enter fullscreen mode Exit fullscreen mode

The result:

Create 1000000 instance, funcs: time(s): size(Bit)
PointNamedTuple: 1.08123s, 0.0546875 Bit
PointDataClass: 1.09183s, 0.046875 Bit
PointDataClassSlots: 1.02618s, 0.046875 Bit
Pointbymsgspec: 0.15777s, 0.046875 Bit
Pointbypydantic: 3.67236s, 0.0703125 Bit
Enter fullscreen mode Exit fullscreen mode

Top comments (0)