Performance issues when using SwiftUI Slider

I am using SwiftUI with RealmSwift and I am currently binding a Realm object’s property to a SwiftUI slider. I noticed that if I keep changing the property with the slider, my cpu usage continues to go up and never drops. If I rapidly move the slider back and forth my gpu drops to as low as 8 fps, which is unacceptable for my video processing app. Any ideas why this is happening? This is what my code looks like:

class Filter: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var id: ObjectId
    @Persisted var filterName: String = ""

    @Persisted var intensity: Float = 1.0

struct FilterPropertiesView: View {
    @ObservedRealmObject var filter: Filter
    var body: some View {
        Slider(value: $filter.intensity, in: 0.0...1.0)

Hi @Shawn_Haghnazari ,

Short answer: don’t do that.

Longer answer: every time you assign a new value to a Realm object property, what happens behind the scenes is that the change becomes a transaction, that needs to be saved in the history and registered into the DB. This in itself isn’t a fast operation, and a big number of small transactions that the slider may push while scrolling are very likely to be queued while the DB machinery tries to find a place for them. Plus, if your realm is synched with MongoDB Realm on Atlas, this also implies a number of additional steps, as in

  • Go through the conflict resolution process, to check if anyone else has changed the same property in the meantime, and check who’s done the modification last
  • Queue the transaction to be sent to the server
  • When the server receives the transaction, it needs to report it into the MongoDB backend, again checking for conflicts, more CPU intensive tasks to execute when they’re not actually needed
  • The transaction is finally registered on the backend: while there are some compactions possible, they’re very conservative to preserve data integrity, so if scrolling your sliders back and forth generates thousands of transactions per minute, they’re likely to stay on the server for a quite some time, using DB space for no reason.

The question is then: do you really need to keep track of all the minute changes the slider will try to save? The most likely answer is no, you need to save just the final value, thus, you can bind the slider to a temporary variable, and save it into the DB when it’s more or less stable.


I see, that makes sense. Thank you for the help!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.