Search code examples
typeormnode.js-typeorm

typeorm create() method is extremely slow


I was using

queryRunner.manager.create(…) 

to create the entity before calling the save method.

I noticed that for a specific customer with lots of data the create step took > 2 sec. when I replaced the create with just creating the new entity myself

const myEntity = new MyEntity();

it made the saving much much faster.

any reason for the create to take so much time? could it be related to the relations this entity has?


Solution

  • The issue was due to the way TypeOrm transforms relations instances in the create() method, it seems that typeOrm is running transform, on each given entity in the create and each of the related entities to it (if you send the full relation instance with its relations in the create() method).

    Before any fixes, my call to create() looked like this:

    const transaction = queryRunner.manager.create(Transaction, {
          seller: sellerInstance,
          buyer: buyerInstance
        });
    

    Solution 1: Sending ids only — if you still want to use create() make sure you don’t send the full relation instance in the create fields, send only the ids. (This field is the only thing you really need as this is the real reference in the table).

    const transaction = queryRunner.manager.create(Transaction, {
      seller: { id: sellerInstance.id },
      buyer: { id: buyerInstance.id },
    });
    

    Solution 2: You can always use new()

    const transaction = new Transaction();
    transaction.seller = sellerInstance;
    transaction.buyer = buyerInstance;
    

    checkout my blog post for additional details on this issue:

    https://tamar-duchovny.medium.com/two-lines-change-turned-a-6-sec-request-to-300ms-cf0f13c00a75