iamkun / iamkun/dayjs

Performance problem: slow format()

Open
#2,400 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
48.7k
Forks
2.5k
PR merge metrics
No merged PRs in 30d

Description

**Describe the bug**
- I want to render a page with a big list of some goods with some dates, e.g. expiration
- I have code similar to
```js
const now = dayjs();
const list = [];
for (const item of goods) {
list.push({
item,
expires: now.add(item.daysLeft).format(`D MMMM YYYY`)
});
}
// render the list
```

This takes too long, because every call to `.format()` does much of work under the hood: https://github.com/iamkun/dayjs/blob/a9d7d0398d22ebd4bfc3812ca0134a97606d54d9/src/index.js#L262-L342

The worst things performance-wise:
- the local functions `getShort`, `get$H`, `meridiemFunc`, `matches` are created on every call, even if not needed
- the same format string `D MMMM YYYY` is processed via `str.replace(C.REGEX_FORMAT, ...)` again and again on every call

**Expected behavior**
I'd like to have a way to preprocess/precompile format string in such a way that the following calls to `format()` will be very fast. E.g.

```js
const now = dayjs();
const list = [];
const precompiledFormat = dayjs.precompileFormat(`D MMMM YYYY`);
for (const item of goods) {
list.push({
item,
expires: now.add(item.daysLeft).format(precompiledFormat),
// or maybe:
expires: precompiledFormat(now.add(item.daysLeft))
});
}
// render the list
```

**Information**
- Day.js Version: 1.9.0
- OS: Mac OS 12
- Browser: Chrome 115

Contributor guide

Open the contributing guide

Research direction

Start by reading the format implementation cited in src/index.js around lines 262-342, focusing on the repeated format-string processing and per-call helper creation. Benchmark repeated formatting of D MMMM YYYY, then define and verify a precompilation API that makes subsequent calls faster while preserving the existing formatted output.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
performance
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.