Skip to content

perf: nested validation is slow  #343

@ljobse

Description

@ljobse

Problem

Validation of a plain object is really fast.
Once an object is nested within another it gets "really" slow

  • Simple single field validation: 0ms
  • Nested 2 level single field validation: 50ms

Question

Can we somehow make it faster? Seems like it doesn't have to be that much more complex?

Example

@Exclude()
class NestedChildValidator {
  @Expose()
  @IsString()
  public text: string;
}

@Exclude()
class ChildValidator {
  @Expose()
  @ValidateNested({each: true})
  @Type(() => NestedChildValidator)
  @ArrayMinSize(1)
  public children: NestedChildValidator[];
}

@Exclude()
class ParentValidator {
  @Expose()
  @ValidateNested({each: true})
  @Type(() => ChildValidator)
  @ArrayMinSize(1)
  public children: ChildValidator[];
}
it('Should throw nested validation error', async () => {
  const val: ParentValidator = {
    children: [{ children: undefined }]
  };

  const input = plainToClass(ParentValidator, val);
  try {
    console.log(Date.now());
    await validate(input);
    expect(false, 'Validator should throw and not continue').to.equal(true);
  } catch (error) {
    console.log(Date.now()); // 50ms after first console log
  }
});

it('Should throw simple validation error', async () => {
  const val: NestedChildValidator = {
    text: undefined
  };

  const input = plainToClass(NestedChildValidator, val);
  try {
    console.log(Date.now());
    await validate(input);
    expect(false, 'Validator should throw and not continue').to.equal(true);
  } catch (error) {
    console.log(Date.now()); // Same time as first console log
  }
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: done/releasedIssue has been completed, no further action is needed.type: fixIssues describing a broken feature.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions