New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TextInput becomes slow after lots of typing #20119

Open
gnprice opened this Issue Jul 9, 2018 · 26 comments

Comments

Projects
None yet
@gnprice
Copy link
Contributor

gnprice commented Jul 9, 2018

Environment

$ react-native info
Environment:
  OS: Linux 4.9
  Node: 8.11.3
  Yarn: 1.7.0
  npm: 5.6.0
  Watchman: Not Found
  Xcode: N/A
  Android Studio: Not Found

Packages: (wanted => installed)
  react: 16.3.1 => 16.3.1
  react-native: 0.56.0 => 0.56.0 (*)

(*) In my test app, actually v0.55.4 plus the patch from #19645 . Others on #19126 report the same symptoms using v0.56.

Description

After typing a lot of text into a controlled TextInput, like ~500 char on a recent fast phone, we start dropping frames. It gets worse the more you type; at ~1000 char, we very frequently drop frames and the app looks noticeably laggy.

Reproducible Demo

The original repro is by @s-nel: https://github.com/s-nel/rn19126

Originally reported at #19126 (comment); more discussion in subsequent comments in that thread.

In particular, here's the video from that repro:
video

Here's a video by @s-nel on my test app, with this description:

Yes I can reproduce from [that repo] after typing for a couple minutes straight. I don't have to clear anything as the original bug description [in #19126] indicates. Here you can see my JS framerate drop to single digits from adding a few characters

image

Here's my description of replicating that repro, again in my test app:

I just tried again with my test app, on RN 0.55.4 + patch. If I type continuously for about 60 seconds -- maybe 400-500 characters, at a rough estimate (just gibberish, both thumbs constantly typing letters) -- then the perf overlay gets to about "10 dropped so far", and zero stutters. If I continue and get up to about 90 seconds, the "dropped" figure climbs faster, and the framerate (in "JS: __ fps") noticeably drops. At about 150 seconds (~1000 characters?), the "dropped" figure rapidly climbs past 200, and the framerate hangs out around 30.

Even at that point, it's still "0 stutters". And if I ignore the perf overlay and try typing normal text and watching it like I were using an app for real: it's a bit laggy, but doesn't make things feel unusable or outright broken, and I think most of the time I wouldn't even notice.

That was on a Pixel 2 XL; the numbers will probably vary with hardware.

Background from previous bug

This bug seems closely related to #19126; the repro steps and symptoms seem to be exactly the same, except quantitatively much less severe. (The original reports of #19126 describe clearing the input as part of the repro; I now think that was probably a red herring.)

The extreme symptoms of #19126 were absent in v0.54, introduced in v0.55, and fixed in v0.56 by #19645 . As I wrote when I figured out the cause of that (leading to the one-line fix in #19645):

[This buggy NaN comparison] means every text shadow node will create a CustomLetterSpacingSpan around its contents, even when the letterSpacing prop was never set. It must be that we're somehow ending up with large numbers of these shadow nodes -- that sounds like a bug in itself, but I guess it's normally low-impact -- and this condition is failing to prune them from causing a bunch of work here.

I think we're now looking at exactly that underlying bug. It may well have been present in v0.54 and earlier releases; I don't think we have any data on that.

I don't know anything more about what causes it; even the hypothesis that we're ending up with large numbers of text shadow nodes is just an inference from how it interacts with the line fixed in #19645. So, more debugging is required.

I don't expect to do that debugging myself, because these remaining symptoms are no longer one of the top issues in our own app. But I hope somebody else will!

@kelset

This comment has been minimized.

Copy link
Collaborator

kelset commented Jul 10, 2018

👋 @gnprice thanks for the writeup, I've added a couple more tags that seem to be more related to the issue.

Sadly AFAIK the TextInput is an hard portion to work with, and currently there is a bit of bus factor in terms of devs that know how it works "deeply". So it may take some time before this get fixed, fingers crossed.

@alp1396

This comment has been minimized.

Copy link

alp1396 commented Jul 10, 2018

After few tests I`ve discovered that clean InputText (without any styling) works normally (sometimes fps going down, but app is not freezing). But if I add some styling to input (e.g. fontSize) then typing process is going to be laggy more and more.

Unstable behavior is appear much faster if quantity of styling options is more. It seems that something went wrong with styling span generation (size, lineHeight, letterSpace and so on) inside of the logic of the text shadow nodes code.

For now, i have to remove all styling from inputs, to get app works.

Maybe that helps someone. Cheers!

@alp1396

This comment was marked as resolved.

Copy link

alp1396 commented Jul 12, 2018

#19500 - Same issue.

@react-native-bot

This comment was marked as outdated.

Copy link
Collaborator

react-native-bot commented Jul 27, 2018

I am closing this issue because it does not appear to have been verified on the latest release, and there has been no followup in a while.

If you found this thread after encountering the same issue in the latest release, please feel free to create a new issue with up-to-date information by clicking here.

@kelset

This comment has been minimized.

Copy link
Collaborator

kelset commented Jul 27, 2018

(ok ignore the bot)

@atopus

This comment has been minimized.

Copy link

atopus commented Aug 16, 2018

Hi,

I'm experiencing the same problem with 3 separate react native apps under developpement.

I have conducted my small tests with the slightlyest modified basic App (but trying with "PureComponent" - see below) with the following versions :

  • 0.54.0
  • 0.55.x series
  • and the 0.56.1 version.

There are differences, but as far as I can tell, the behaviour is basically the same : performances drop after a couple of hundreds of typing (300 words / 1000 carateres). So, could this be inherent to react native &/or mobile dev ?

There are aggravating factors, though :

  • Maybe, as @alp1396 reported above, text styling is a "bug" amplifier, I haven' tried
  • With 0.55.x (not tested with 0.54 nor 0.56), when <TextInput onChange={this._onChange} value={this.state.value} /> is replaced by <TextInput onChangeText={this._onChange}>{this.state.value}</TextInput>, performances are dramatically decreased (but this is not "by the book" anyway). 0fp is reached after 500 caracters or so. ;
  • With no value={this.state.value} inside the TextInput component, it is much better. At 1200 caracters, it is still around 45-55fps, which is acceptable.

My projects must allow the user to compose large pieces of texts, so I guess I will keep an eye on it, and try various workarounds to mitigate it (unmount the component + no value={this.state.value} when admissible...).

Thanks a lot for any update on this issue.


import React from 'react';
import { StyleSheet, Text, View, TextInput } from 'react-native';

export default class App extends React.PureComponent {

  constructor(props) {
    super(props)
    this.state = {
      label : ''
    }
  }

  _onChange = (label) => {
    this.setState({ label })
  }

  render() {
    return (
      <View style={styles.container}>
       <Text>Caracter count : {this.state.label.length}</Text>
        <Text>Word count : {this.state.label.split(' ').length}</Text>
        <TextInput 
          onChangeText={this._onChange}
          value={this.state.label}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
@pluberski

This comment has been minimized.

Copy link

pluberski commented Aug 17, 2018

I don't know if this is in any way helpful, but I started dev-ing on an earlier RN version for my app (I think it might have been .53) and didn't notice the slowdown issue until after I had upgraded my RN version to .55 (and now also seeing it in .56). To wit, not 100% SURE it wasn't there back then, but it does make me wonder if something introduced in .54 might be causing the issue.

@stueynet

This comment has been minimized.

Copy link

stueynet commented Aug 18, 2018

This issue started in 0.54 and still exists today. Any chat app that uses a text input that persists between messages becomes unusable after only a few minutes if chatting. I wish there was some way to get this fixed.

@s-nel

This comment has been minimized.

Copy link

s-nel commented Aug 19, 2018

@stueynet a workaround for chat is to force React to unmount and remount on the text input when the user sends a message.

@jerson-av

This comment has been minimized.

Copy link

jerson-av commented Sep 5, 2018

for me the solution was to do the following

https://snack.expo.io/@jerson/text-input-slow-fix

 _onChange = (label) => {
     if (this.timeoutUpdate) {
      clearTimeout(this.timeoutUpdate);
    }
    this.timeoutUpdate = setTimeout(() => {
      this.input.setNativeProps({
        text: label
      });
    }, 100);

    this.setState({ label })
  }
@oe5wei

This comment has been minimized.

Copy link

oe5wei commented Sep 7, 2018

Any updates on that? Still reproducible in 0.57rc4. Just create a new react native project and use this simple App class:

export default class App extends Component<Props> {
    render() {
        return (
            <TextInput />
        );
    }
}

As the TextInput is unstyled, you won't see it, just click in the top left corner, then the cursor appears. After several recursions (3-5) of typing and clearing the whole text, the lag is noticable, from then on the lag increases every time you clear. On our test device, also other apps are slow then, e.g. the Chrome address bar lags just like the RN TextInput. Only a restart of the device fixes it, but it appears again after some recursions of typing and clearing.

@chris-divvito

This comment has been minimized.

Copy link

chris-divvito commented Sep 10, 2018

OK I have been elbows deep in this issue for a week, I would not have considered myself strong on the Native code side of things, but I think I can at least confirm the original hypothesis that large numbers of spans are being created...

By attaching a breakpoint in /com/facebook/react/views/textinput/ReactEditText.class:395 (manageSpans() method) I can see that as the input is used the number of CustomLineHeight spans on it grows continuously, not being removed when the input is cleared or the text the span affects is deleted. From my understanding this could be other styling spans too - it just happens to be customLineHeight spans in my case because that is the styling I am using.

From what I can tell this is caused by the combination of a few things -

  1. The CustomLineHeight class is not one of the classes checked at the start of manageSpans() in:
      // Remove all styling spans we might have previously set
      if (ForegroundColorSpan.class.isInstance(spans[spanIdx]) ||
          BackgroundColorSpan.class.isInstance(spans[spanIdx]) ||
          AbsoluteSizeSpan.class.isInstance(spans[spanIdx]) ||
          CustomStyleSpan.class.isInstance(spans[spanIdx]) ||
          ReactTagSpan.class.isInstance(spans[spanIdx])) {
        getText().removeSpan(spans[spanIdx]);
      }
  1. Although in sameTextForSpan() it specifically checks to see if the span is for a section of text that no longer exists, and does not add the span to the new SpannableStringBuilder it is building to replace the existing text with, this doesn't help because...
  2. back in maybeSetText() we call getText().replace(0, length(), spannableStringBuilder); however this replaces the text spans from 0 to the new length, not the old one, leaving the spans related to deleted text alive and kicking.

I tried changing the second param to the previous length of the text, however unfortunately this makes the Editable throw and out of range exception as it already considers it's length to be that of the new text (Even though it is still hanging on to the references to the spans that run outside of that new text's bounds).

What did seem to help for me was to add CustomLineHeight as one of the classes to check for the removal of style spans. As above - this just happens to be the styling spans that I am using, but other use cases may need other span classes added there. Seeing as the span is being removed directly, rather than replaced, it seems to work out.

What this does not explain is the experiencing of this issue without clearing or deleting text - that I have no clue about - but certainly as per @netdesk and @stueynet above I was still seeing the performance issues after clearing text even after applying the patch from #19645 .

Hopefully this points someone with more knowledge of the Android TextInput code in the right direction

@sintylapse

This comment has been minimized.

Copy link

sintylapse commented Sep 17, 2018

For me the only stable solution to avoid any lags is to use uncontrolled TextInput which means DON'T use value field. You can manage that in 2 ways:

  1. Use _lastNativeText...
addNewTodo = () => {
    const value = this.addTodoRef._lastNativeText

    if (value) {
        this.props.actions.addTodo(value)
    }
}

render() {
    <TextInput
        ref={component => { this.addTodoRef = component }}
        onSubmitEditing = {this.addNewTodo}
        blurOnSubmit
    />
}

but in this case this.addTodoRef.clear() and this.addTodoRef.setNativeProps({text: ''}) will not empty _lastNativeText, so this solution requires even more hacks above that

  1. Use onChangeText with class property
textInputValue = null

addNewTodo = () => {
    const value = this.textInputValue

    if (value) {
        this.props.actions.addTodo(value)
        this.addTodoRef.clear()
        this.textInputValue = null
    }
}

onChangeText = (text: string) => {
    this.textInputValue = text
}

render() {
    <TextInput
        ref={component => { this.addTodoRef = component }}
        onSubmitEditing = {this.addNewTodo}
        blurOnSubmit
        onChangeText={this.onChangeText}
    />
}
@Yarkhan

This comment has been minimized.

Copy link

Yarkhan commented Sep 18, 2018

Thank you so much @sintylapse!!!!

@stueynet

This comment has been minimized.

Copy link

stueynet commented Sep 18, 2018

So @gnprice can we confirm this is still not fixed even in 0.57 and the issue seems to be related to the value prop on the text input. Using the @sintylapse hack above the issue does not appear to be a problem. Perhaps this will help in terms of figuring out a solution?

To summarize 0.54 and 0.55 are essentially unusable on Android. 0.56 has a partial mitigation of the problem which lets you type for longer but likely will start to be problematic just after more typing.

@Yarkhan

This comment has been minimized.

Copy link

Yarkhan commented Sep 18, 2018

Just a reminder - On iOS, TextInputRef.clear() is not working on v0.54. A check in Platform.OS is needed before applying the hack @sintylapse provided.
#18272

@oe5wei

This comment has been minimized.

Copy link

oe5wei commented Sep 18, 2018

We did a lot of experimenting in the last days, and our issue is clearly linked to the Google Keyboard app. I don't know if it's the exact same issue like this one discussed here, because we could reproduce it down to RN 0.50 (simple app with just a TextInput like my example above). In 0.49 it was not reproducible, from 0.50 to 0.57rc4 we could reproduce it. In our current app in development an external keyboard is used, it's easier to reproduce then because you can hammer the physical keys, CTRL+A, Delete, hammer again, and repeat that a couple of times until it becomes slower and slower. We tried to reset our test devices, after reset the slowness was gone, until the Google Keyboard updated in the background from 4.* to 7.* - then the slowness immediately touched in. Downgrading Google Keyboard to 4.* or deactivating it totally fixes the issue immediately. We tried some other keyboards. With Swift keyboard it's slow too, there you see that our test device does hard work when updating swift's vocabulary suggestions, but it's usable and doesn't slow down with every cleaning of the input - it's just a bit slow from the beginning. Other keyboards like Chrooma or Go also introduce some slowness, but you only see it if you hammer the physical keys with flat hands and fingers, not if you type normally. With Google Keyboard 7.* enabled, it becomes slower and slower with every clearing of the TextInput. If you disable voice keyboard and then uninstall all keyboard apps, (you can't disable the voice keyboard when it's the only keyboard left so you have to disable it before you uninstall the last keyboard app), so, there is no software keyboard left, then there is zero slowness, nothing. Maybe it's not directly related to this issue, but at least the effect is the same.

@hoangvuanhdevelopervn

This comment has been minimized.

Copy link

hoangvuanhdevelopervn commented Nov 9, 2018

@oe5wei You write a story?

@piubellofelipe

This comment has been minimized.

Copy link

piubellofelipe commented Nov 9, 2018

Any updates on this issue? Really annoying bug :(

@illestrater

This comment has been minimized.

Copy link

illestrater commented Nov 9, 2018

@piubellofelipe I'd recommend using @sintylapse's temporary solution until it's fixed. Graceful enough for me in the meantime!

@hoangvuanhdevelopervn

This comment has been minimized.

Copy link

hoangvuanhdevelopervn commented Nov 12, 2018

Nothing change?

@pandanr1

This comment has been minimized.

Copy link

pandanr1 commented Nov 26, 2018

Same problem here. This Issue is from july... TextInput is a very ... very critical feature!

 React Native Environment Info:
    System:
      OS: macOS High Sierra 10.13.6
      CPU: x64 Intel(R) Core(TM) i5-4278U CPU @ 2.60GHz
      Memory: 88.79 MB / 16.00 GB
      Shell: 3.2.57 - /bin/bash
    Binaries:
      Node: 8.12.0 - /usr/local/bin/node
      npm: 6.4.1 - /usr/local/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: iOS 12.1, macOS 10.14, tvOS 12.1, watchOS 5.1
    IDEs:
      Android Studio: 3.1 AI-173.4907809
      Xcode: 10.1/10B61 - /usr/bin/xcodebuild
    npmPackages:
      react: 16.5.0 => 16.5.0 
      react-native: 0.57.0 => 0.57.0 
    npmGlobalPackages:
      create-react-native-app: 1.0.0
      react-native-cli: 2.0.1
@kelset

This comment has been minimized.

Copy link
Collaborator

kelset commented Nov 26, 2018

AFAIK there is no PR directly related to this issue currently open, feel free to implement something if you can.

There are currently a lot of things going on with the repo, so I have no estimate on when this can be picked up.

Alastair-smith2 added a commit to Alastair-smith2/react-native-gifted-chat that referenced this issue Dec 11, 2018

@LzxHahaha

This comment has been minimized.

Copy link

LzxHahaha commented Dec 29, 2018

0.57.7 still have this problem

@LzxHahaha

This comment has been minimized.

Copy link

LzxHahaha commented Dec 29, 2018

For me the only stable solution to avoid any lags is to use uncontrolled TextInput which means DON'T use value field. You can manage that in 2 ways:

  1. Use _lastNativeText...
addNewTodo = () => {
    const value = this.addTodoRef._lastNativeText

    if (value) {
        this.props.actions.addTodo(value)
    }
}

render() {
    <TextInput
        ref={component => { this.addTodoRef = component }}
        onSubmitEditing = {this.addNewTodo}
        blurOnSubmit
    />
}

but in this case this.addTodoRef.clear() and this.addTodoRef.setNativeProps({text: ''}) will not empty _lastNativeText, so this solution requires even more hacks above that

  1. Use onChangeText with class property
textInputValue = null

addNewTodo = () => {
    const value = this.textInputValue

    if (value) {
        this.props.actions.addTodo(value)
        this.addTodoRef.clear()
        this.textInputValue = null
    }
}

onChangeText = (text: string) => {
    this.textInputValue = text
}

render() {
    <TextInput
        ref={component => { this.addTodoRef = component }}
        onSubmitEditing = {this.addNewTodo}
        blurOnSubmit
        onChangeText={this.onChangeText}
    />
}

This is a good way, but it will still slow down after a thousand edits.

demo gif link

Here is a demo

@pandanr1

This comment was marked as disruptive content.

Copy link

pandanr1 commented Jan 3, 2019

The above does not work(and should! because a standard-text-input should just work!). Please update main-readme with the following text: TEXT-INPUT DOES NOT WORK! Because THIS is a SHOWSTOPPER for any app but it takes some useless time debugging(and writing an entire app based on RN) to get it.

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