Skip to content

Conversation

ssi02014
Copy link

@ssi02014 ssi02014 commented May 12, 2025

@typicode 👋

Thank you for providing such a great library. I have created this pull request to give you suggestions to improve the performance of json-sever.

We can improve performance by changing Object.fromEntries + entries + map + filter to Object.keys + forEach.

In my benchmark tests, I verified a performance improvement of about 4.3x or more for the latter.

We can also define the type for query a bit more clearly.

benchmark

스크린샷 2025-05-12 오후 5 41 51
// Test Code
import { bench, describe } from 'vitest';

describe('query transformation', () => {
  const req = {
    query: {
      _start: '10',
      _end: '20',
      _limit: 'invalid',
      _page: '2',
      _per_page: '10',
      search: 'test',
      filter: 'active',
      nan: NaN,
    },
  };

  bench('Object.fromEntries + Object.entries + map + filter', () => {
    const query = Object.fromEntries(
      Object.entries(req.query)
        .map(([key, value]) => {
          if (
            ['_start', '_end', '_limit', '_page', '_per_page'].includes(key) &&
            typeof value === 'string'
          ) {
            return [key, parseInt(value)];
          } else {
            return [key, value];
          }
        })
        .filter(([, value]) => !Number.isNaN(value))
    );
  });

  bench('Object.keys + forEach', () => {
    const query = {};
    Object.keys(req.query).forEach((key) => {
      let value = req.query[key];

      if (
        ['_start', '_end', '_limit', '_page', '_per_page'].includes(key) &&
        typeof value === 'string'
      ) {
        value = parseInt(value);
      }

      if (!Number.isNaN(value)) {
        query[key] = value;
      }
    });
  });
});

Test

The test code also all passes fine. 🤗


스크린샷 2025-05-12 오후 5 37 17

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant