Skip to content

Date 800x slower than JSC #930

Open
Open

Description

@burakgormek

Bug Description

Date so slow that it can be freeze app. Impossible to use third party date library(much worse perf, 1800x).
I found that local date is a problem. UTC date still slow but not 800x, just 8x slower than JSC which can be ignored.

The code outputs:
JSC: 0.2605330003425479
Hermes: 166.44708999991417
Hermes UTC: 1.6460870001465082

  • I have run gradle clean and confirmed this bug does not occur with JSC

Hermes version: Bundled version with RN 0.71.3
React Native version (if any): 0.71.3
OS version (if any): iPhone 14 (simulator)
Platform (most likely one of arm64-v8a, armeabi-v7a, x86, x86_64):

Steps To Reproduce

  1. Create initial app with latest RN version.
  2. Add somewhere the code that down below. Look console to see the numbers.

code example:

var a = performance.now();
Array(1000)
  .fill(0)
  .map(() => {
    new Date(new Date().setMonth(1));
    // fast utc version 
    // new Date(new Date().setUTCMonth(1));
  });
var b = performance.now();

console.log(b - a);

The Expected Behavior

Fast Date operations.

Activity

  1. added
    bug
    on Mar 3, 2023
  2. tmikov commented on Mar 4, 2023

    @tmikov
    Contributor

    Thank you for reporting this. It looks like an actual problem and is likely caused by us not caching the timezone information.

    As an experiment, we changed the system timezone while the JS process was running to see whether it would invalidate the timezone. Hermes displayed the correct new timezone, while JSC and v8 displayed the original one. It is not entirely clear which behavior is preferable.

    Could you try a similar experiment in your mobile app?

  3. ljukas commented on Mar 6, 2023

    @ljukas

    I can confirm this, I previously used spacetime js to simplify date comparisons in my expo managed app. With the newest release of expo 48 we transitioned to hermes engine and had to remove all spactime js uses because just 150 items slowed down the app to a standstill for several seconds whilst running date comparisons.

    This is now our code:

    image

    And this is also slower than it was using jsc, by a large margin.

  4. rpopovici commented on Mar 6, 2023

    @rpopovici

    @tmikov this is a major problem for anything which relies on dates to generate unique identifiers or localized translations..

    Both iOS and android have mechanisms to notify the app when there is a timezone change.
    https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622992-applicationsignificanttimechange
    https://developer.android.com/reference/android/content/Intent#ACTION_TIMEZONE_CHANGED

    IMO, caching the timeszone info and then updating that info only when there is an actual timezone change could be a potential solution here.

  5. added
    enhancement
    and removed
    bug
    on Mar 16, 2023
  6. DePavlenko commented on Apr 27, 2023

    @DePavlenko

    We have exactly the same issue. Because of it we cannot switch to Hermes engine unfortunately.

    I run this function in a sorting loop (~500 items in a list)

    const isSameDay = (date1: Date, date2: Date) =>
      date1.getFullYear() === date2.getFullYear() &&
      date1.getMonth() === date2.getMonth() &&
      date1.getDate() === date2.getDate();
    

    Here is a preview:


    And then I tried to use isSame function form dayjs and it took ~15500ms!!! to complete sorting

  7. tmikov commented on Apr 27, 2023

    @tmikov
    Contributor

    We agree that this needs to be fixed to match the behavior of the other engines. Unfortunately we don't have concrete plans on when exactly we can work on the fix yet. Meanwhile a community contribution would be welcome.

  8. DePavlenko commented on Apr 28, 2023

    @DePavlenko

    Thank you for the quick response @tmikov!
    I just wonder how people handle it in their projects at the moment (don't use Hermes?). It's quite hard to find any opened issues or articles about the problem but I think almost every project has some interactions with dates

  9. harrigee commented on Apr 28, 2023

    @harrigee

    Thank you for the quick response @tmikov!
    I just wonder how people handle it in their projects at the moment (don't use Hermes?). It's quite hard to find any opened issues or articles about the problem but I think almost every project has some interactions with dates

    The "solution" in our case is indeed not using Hermes atm.

  10. rpopovici commented on Apr 28, 2023

    @rpopovici

    @tmikov The simplest most straight forward solution here would be to expose an API from hermes which will cache the timezone info on demand instead of doing it automatically on every call.

  11. tmikov commented on May 18, 2023

    @tmikov
    Contributor

    @rpopovici are there APIs for updating the cached timezone information in JSC? In other words, if a RN app is running in JSC and a system timezone change occurs, how can you force it to refresh its cache? If there is no such API, how can the app handle timezone changes at all?

  12. rpopovici commented on May 18, 2023

    @rpopovici

    @tmikov if relying on timezone change events is a deviation from the standard behaviour, then trying to debounce the timezone info every second could be an acceptable compromise solution which could alleviate the perf bottleneck and is better than JSC or v8 since these two won't update the timezone data at all.

    Also the timezone debouncing solution can be easily exposed through a hermes runtime config flag and then you can keep both behaviours and let the user decide if they need super accurate timezone info or they can settle for something less accurate but more performant

  13. 43 remaining items

  14. evelant commented on Dec 8, 2023

    @evelant

    @TiStyle I refactored all of my code to avoid Date instances (except for display in the UI). I just use plain numbers and do simple math when I need to add/subtract/calculate things. Use Date.now() to get a number instead of a Date.

  15. TiStyle commented on Dec 11, 2023

    @TiStyle

    @evelant I was hoping to avoid such things, but it seems there is no other solution but for now(). Haha, get it?.. Thank you for your advice, I'll just have to start this painstakingly task.

  16. tj-mc commented on Mar 26, 2024

    @tj-mc

    I wanted to share that we are also facing this issue in our React Native app.

    We have an infinite list of messages, each of which render a date, which must be calculated by the difference between sendTime and now.

    To "solve" this, we can eagerly render the list, then defer the date calculations inside InteractionManager. This greatly sped up the initial paint of the list.

    /**
     * DateTime calculation are currently very slow in Hermes https://github.com/facebook/hermes/issues/930
     * This means each MessageTime would add about 20ms to the list item render.
     *
     * To 'resolve' this, we start with empty string, then wrap the formatFunction in InteractionManager,
     * so that it does block the first paint. This tradeoff is that the timestamp loads slightly after the message,
     * but the message list renders in 1/3rd the time.
     *
     * This optimisation can be removed when the above issue is solved.
     *
     */
    export const MessageTime = ({ timestamp, prefix }: Props) => {
      const [text, setText] = useState('');
    
      useEffect(() => {
        const calculateStamp = () =>
          InteractionManager.runAfterInteractions(() => {
            setText(formatTimestamp(new Date(), timestamp));
          });
    
        calculateStamp();
    
        const interval = setInterval(() => {
          calculateStamp();
        }, oneMinute);
    
        return () => clearInterval(interval);
      }, [timestamp]);
    
      return (
        <View style={styles.container}>
          <Text muted fontSize={'sm'} numberOfLines={1}>
            {prefix}
            {text}
          </Text>
        </View>
      );
    };
    
    const styles = StyleSheet.create({
      container: {
        display: 'flex',
        flexDirection: 'row',
        flexShrink: 1,
      },
    });
  17. gaberogan commented on Mar 29, 2024

    @gaberogan

    In our case DayJS was the problem, so I made some quick performance improvments and it now runs 1000x faster on iOS simulator:

    NOTE: See @km-tr 's comment below to address using dayjs().set(...) as my solution does not account for mutability.

    diff --git a/node_modules/dayjs/esm/index.js b/node_modules/dayjs/esm/index.js
    index a82986b..1fb8898 100644
    --- a/node_modules/dayjs/esm/index.js
    +++ b/node_modules/dayjs/esm/index.js
    @@ -117,17 +117,101 @@ var Dayjs = /*#__PURE__*/function () {
     
       _proto.init = function init() {
         var $d = this.$d;
    -    this.$y = $d.getFullYear();
    -    this.$M = $d.getMonth();
    -    this.$D = $d.getDate();
    -    this.$W = $d.getDay();
    -    this.$H = $d.getHours();
    -    this.$m = $d.getMinutes();
    -    this.$s = $d.getSeconds();
    -    this.$ms = $d.getMilliseconds();
    +    // this.$y = $d.getFullYear();
    +    // this.$M = $d.getMonth();
    +    // this.$D = $d.getDate();
    +    // this.$W = $d.getDay();
    +    // this.$H = $d.getHours();
    +    // this.$m = $d.getMinutes();
    +    // this.$s = $d.getSeconds();
    +    // this.$ms = $d.getMilliseconds();
       } // eslint-disable-next-line class-methods-use-this
       ;
     
    +  // Avoid running native Date functions like getFullYear until needed because these
    +  // functions are super slow in Hermes. Then run once and cache since Dayjs is immutable.
    +
    +  Object.defineProperty(Dayjs.prototype, '$y', {
    +    get() {
    +      if (!this.cached_y) {
    +        this.cached_y = this.$d.getFullYear();
    +      }
    +      return this.cached_y;
    +    }
    +  });
    +
    +  Object.defineProperty(Dayjs.prototype, '$M', {
    +    get() {
    +      if (!this.cached_M) {
    +        this.cached_M = this.$d.getMonth();
    +      }
    +      return this.cached_M;
    +    }
    +  });
    +
    +  Object.defineProperty(Dayjs.prototype, '$D', {
    +    get() {
    +      if (!this.cached_D) {
    +        this.cached_D = this.$d.getDate();
    +      }
    +      return this.cached_D;
    +    }
    +  });
    +
    +  Object.defineProperty(Dayjs.prototype, '$W', {
    +    get() {
    +      if (!this.cached_W) {
    +        this.cached_W = this.$d.getDay();
    +      }
    +      return this.cached_W;
    +    }
    +  });
    +
    +  Object.defineProperty(Dayjs.prototype, '$H', {
    +    get() {
    +      if (!this.cached_H) {
    +        this.cached_H = this.$d.getHours();
    +      }
    +      return this.cached_H;
    +    }
    +  });
    +
    +  Object.defineProperty(Dayjs.prototype, '$m', {
    +    get() {
    +      if (!this.cached_m) {
    +        this.cached_m = this.$d.getMinutes();
    +      }
    +      return this.cached_m;
    +    }
    +  });
    +
    +  Object.defineProperty(Dayjs.prototype, '$s', {
    +    get() {
    +      if (!this.cached_s) {
    +        this.cached_s = this.$d.getSeconds();
    +      }
    +      return this.cached_s;
    +    }
    +  });
    +
    +  Object.defineProperty(Dayjs.prototype, '$ms', {
    +    get() {
    +      if (!this.cached_ms) {
    +        this.cached_ms = this.$d.getMilliseconds();
    +      }
    +      return this.cached_ms;
    +    }
    +  });
    +
    +  Object.defineProperty(Dayjs.prototype, '$timezoneOffset', {
    +    get() {
    +      if (!this.cached_timezoneOffset) {
    +        this.cached_timezoneOffset = this.$d.getTimezoneOffset();
    +      }
    +      return this.cached_timezoneOffset
    +    }
    +  });
    +
       _proto.$utils = function $utils() {
         return Utils;
       };
    @@ -137,15 +221,27 @@ var Dayjs = /*#__PURE__*/function () {
       };
     
       _proto.isSame = function isSame(that, units) {
    +    if (units === undefined) {
    +      return this.toISOString() === dayjs(that).toISOString()
    +    }
    +
         var other = dayjs(that);
         return this.startOf(units) <= other && other <= this.endOf(units);
       };
     
       _proto.isAfter = function isAfter(that, units) {
    +    if (units === undefined) {
    +      return this.toISOString() > dayjs(that).toISOString()
    +    }
    +
         return dayjs(that) < this.startOf(units);
       };
     
       _proto.isBefore = function isBefore(that, units) {
    +    if (units === undefined) {
    +      return this.toISOString() < dayjs(that).toISOString()
    +    }
    +
         return this.endOf(units) < dayjs(that);
       };
     
    @@ -408,7 +504,7 @@ var Dayjs = /*#__PURE__*/function () {
       _proto.utcOffset = function utcOffset() {
         // Because a bug at FF24, we're rounding the timezone offset around 15 minutes
         // https://github.com/moment/moment/pull/1871
    -    return -Math.round(this.$d.getTimezoneOffset() / 15) * 15;
    +    return -Math.round(this.$timezoneOffset / 15) * 15;
       };
     
       _proto.diff = function diff(input, units, _float) {
  18. efstathiosntonas commented on Mar 29, 2024

    @efstathiosntonas

    I noticed 150ms increase in render time with dayjs, without the date the component rendered in 50ms, converted to Date and it increased to 70ms which is way faster than the 200ms with dayjs.

  19. km-tr commented on May 21, 2024

    @km-tr

    @gaberogan
    I tried your patch, but I encountered an issue where executing something like dayjs(date).day(0) causes the date to shift. Have you addressed this problem?

    For example, today is the 22nd, and when I use day(0), I expect it to return the 19th, but it returns the 22nd instead.

    However, when I use add(1), it correctly returns the 20th.

  20. gaberogan commented on May 22, 2024

    @gaberogan

    @km-tr I haven't seen this problem, but thanks for mentioning it. If it's a problem with my diff and you find a solution, I'll update the diff so others don't run into the same problem.

  21. km-tr commented on May 22, 2024

    @km-tr

    @gaberogan

    Thank you for checking.
    After trying various solutions myself, I found that initializing the cache within init resolved the issue.
    It seems that init is executed at the end of $set within dayjs, and if the cache isn’t initialized, the cached value is used instead of the value set by $set.

     _proto.init = function init() {
        this.cached_y = undefined;
        this.cached_M = undefined;
        this.cached_D = undefined;
        this.cached_W = undefined;
        this.cached_H = undefined;
        this.cached_m = undefined;
        this.cached_s = undefined;
        this.cached_ms = undefined;
        this.cached_timezoneOffset = undefined;
      }
  22. km-tr commented on May 23, 2024

    @km-tr

    @gaberogan
    https://github.com/km-tr/dayjs

    Since importing dayjs/esm caused other issues, I forked the repository to address them.
    For now, I’m installing from GitHub, so I have included the build files in the commit.

  23. lavenzg commented on Jun 26, 2024

    @lavenzg
    Contributor

    We have made some improvements to localTime()/utcTime() performance in Hermes. On a simple benchmark with pure Date usage in a loop, it should have performance comparable to V8/JSC. On the dayjs benchmark above, it's ~2X faster than before (still ~2X slower than V8 but the main bottleneck is not very relevant to Date and Time computations now).

  24. vomchik commented on Jun 27, 2024

    @vomchik

    @lavenzg Thank you! Do you know when we can expect this fix in the RN?

  25. tj-mc commented on Sep 18, 2024

    @tj-mc

    HI there, it has been a few months now and we're very eager to find a solution to this.
    We're using Luxon, as well as normal Date objects. Our applications has hundreds of timers and countdowns, so it's having a massive effect on performance. It's not realistic to re-write everything without Date(). Is there any update on when this will merge?

  26. neildhar commented on Sep 18, 2024

    @neildhar
    Contributor

    The performance improvements were made in 59ea64c, and should be part of RN 0.76.

  27. RohovDmytro commented on Mar 9, 2025

    @RohovDmytro

    Can somebody confirm that their performance issues related to manipulations of lots of Dates objects got resolved in 0.77.*+?

  28. tj-mc commented on Apr 22, 2025

    @tj-mc

    In our application @ .77, there is huge improvement and we removed the workaround. Thanks RN Team.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions