Skip to content

Peformance on attribute access #4462

@exrich

Description

@exrich

I have found that accessing object attributes on SQLAlchemy is very slow. For example

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
import time

Base = declarative_base()


class A(Base):

    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)


class B:

    def __init__(self, id):

        self.id = id


e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)

s = Session(e)

a1 = A(id=1)
b1 = B(1)

%timeit a1.id
298 ns ± 5.14 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit b1.id
31.1 ns ± 0.477 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

approx 10 times slower to lookup the value of an attribute. The difference is much less if I do this:

%timeit a1.__dict__['id']
72.3 ns ± 15.8 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In my actual code I'm getting an object from the db then making it transient to perform some intensive computations but this attribute access is really slowing everything down. Should I be doing something else to remove the object from sqlalchemy whilst I do these computations?

Thx

Metadata

Metadata

Assignees

No one assigned

    Labels

    ormperformancewhere performance can be improved. add "bug" only if it's a performance degradationquestionissue where a "fix" on the SQLAlchemy side is unlikely, hence more of a usage questionwontfix / out of scopesomething we decided we aren't doing, for whatever reason

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions