2

I have a quite data-heavy app I'm working on, and I can see in Chrome's profiler that moment is chewing up an enormous amount of CPU when working with large datasets. I'm aware it's reasonably well-known for this, but I don't know how I'd format timezones with a native Date object. Is it achievable?

For what it's worth, the super expensive function I've written is this:

export const formatByTimeZone = date => {
    const userTimezone = moment.tz.guess()

    moment.tz.setDefault('Australia/Melbourne')

    const returnValue = moment(date).tz(userTimezone)

    moment.tz.setDefault()

    return returnValue
}

Our API uses Melbourne time, so it just converts that to the user's time.

MitchEff
  • 1,417
  • 14
  • 29

2 Answers2

0

I think you should try date-fns

Momentjs has his all functions as member function. So you have to import all functions even you need only ‘Add’ function. Once you create a instance, all function are included. date-fns is divided by function level. So you can import and use only what you need.

Becuase of this reason, in result of build on web application, generally momentjs has more size than date-fns.(no tree shaking) - more

Wadu
  • 107
  • 1
  • 12
0

You can optimize your function as below

const userTimezone = moment.tz.guess();
export const formatByTimeZone = date => {
    const returnValue = moment(date, 'Australia/Melbourne').tz(userTimezone);
    return returnValue;
}
  1. get and set userTimezone in variable once instead of doing it everytime when formatted

  2. Don't change default timezone everytime when formatted

Santhosh S
  • 782
  • 5
  • 17
  • Thanks, Santhosh. I believe the primary issue is Moment itself is rather slow compared to other packages (or native Date()). I'll give this a try, though. Thanks! – MitchEff Jan 08 '20 at 23:51