loopbackio / loopbackio/loopback-next

Performance issues with ModelUtils._coerce and coerceArray

Open
#9,501 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
TypeScript
Stars
5.1k
Forks
1.1k
Avg merge
2d 21h
Merged PRs (30d)
27

Description

Describe the bug

The way ModelUtils._coerce uses coerceArray is inefficient, and is causing it to show up as 20% of my application's CPU usage in profiler runs under a create heavy workload.

The problem code is this in juggler:

    try {
      // Coerce val into an array if it resembles an array-like object
      val = coerceArray(val);
    } catch (e) {
      // NOOP when not coercable into an array.
    }

Throwing and catching an error is much more expensive than returning a value, and nearly every call to _coerce hits this try/throw/catch path.

image

A variant of coerceArray that doesn't throw, but instead returns [arrayVal | undefined, coerced: boolean] I think would fix the performance problem here.

Logs

No response

Additional information

No response

Reproduction

design issue

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in lib/model-utils.js around lines 498-503, where ModelUtils._coerce calls coerceArray inside the try/catch path. Review coerceArray's behavior and the create-heavy workload described in the issue, then verify that coercion preserves existing behavior without the repeated exception cost and confirm the improvement with profiling.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
backend, performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.