mParticle / mparticle-apple-sdk

mParticle Apple SDK
Apache License 2.0
45 stars 66 forks source link

MParticle runs methods explicitly on the main thread why and how to mitigate the impact #284

Closed angelstoone closed 1 month ago

angelstoone commented 1 month ago

Hi team 👋🏻

I noticed while improving the app start of our iOS application that several methods of the MParticle SDK are explicitly run on the main thread, the more costly seems to be

Thank you 😃

angelstoone commented 1 month ago

Confirmed the MParticleWebView point since it's mentioned in the documentation 👍🏻 Question though, why aren't you caching it after retrieving it 🤔?

einsteinx2 commented 1 month ago

Hi thanks for reporting these concerns.

Regarding the calling of initializeKits from the main thread, I took a quick look and it does appear that a lot of that logic could likely be performed in the background.

When starting kits, we are also initializing partner SDKs, some of which expect to be initialized on the main thread in the app delegate's didFinishLaunching method on app launch, so we'll need to evaluate that on a case by case basis to ensure we don't break any functionality, but in the meantime we should be able to at least move a lot of the other mParticle internal logic into the background and only call into the main thread to do the final kit (and therefore partner SDK) initialization.

I've created an internal ticket to investigate improving that, but can't provide an ETA at this time. If needed, please escalate with your customer service manager or account representative.

Confirmed the MParticleWebView point since it's mentioned in the documentation 👍🏻 Question though, why aren't you caching it after retrieving it 🤔?

We are caching the user agent in the resolvedAgent property.

Note that the evaluateAgent method is only called by the startCollectionIfNecessary which is only called once by the startWithCustomUserAgent method. The result is then stored in the resolvedAgent property. There's only one instance of the MParticleWebView class created which is owned by the main mParticle class, and stored as a property.

It's only initialized once on in the init method of the mParticle class, so only once when first starting the SDK. We must do this in the main thread because WKWebView is a UIKit class and must be used on the main thread.

As you noted, you can pass a custom user agent if this main thread usage is an issue for your application.