title: How to improve performance for large datasets with Realm?
body: <p>My database has 500,000 records. The tables don't have a primary key because Realm doesn't support compound primary keys. I fetch data in background thread, then I want to display it in the UI on the main thread. But since Realm objects cannot be shared across threads I cannot use the record I fetched in the background. Instead I need to refetch the record on main thread? If I fetch a record out of the 500,000 records it will block the main thread. I don't know how to deal with it. I use Realm because it said it's enough quick. If I need refetch the record many times, is it really faster than SQLite? I don't want to create another property that combine other columns as primary key because the Realm database is already bigger than a SQLite file.</p>
  
  <pre><code>@objc class CKPhraseModel: CKBaseHMMModel{
      dynamic var pinyin :String!
      dynamic var phrase :String = ""
  
      class func fetchObjects(apinyin :String) -&gt; Results&lt;CKPhraseModel&gt; {
  
          let realm = Realm.createDefaultRealm()
  
          let fetchString = generateQueryString(apinyin)
          let phrases = realm.objects(self).filter(fetchString).sorted("frequency", ascending: false)
  
          return phrases
      }
  
      func save(needTransition :Bool = true) {
  
          if let realm = realm {
              try! realm.write(needTransition) {[unowned self] in
                  self.frequency += 1
              }
          }
          else {
              let realm = Realm.createDefaultRealm()
              if let model = self.dynamicType.fetchObjects(pinyin).filter("phrase == %@", phrase).first {
                  try! realm.write(needTransition) {[unowned self] in
                      model.frequency += self.frequency
                  }
              }
              else {
                  try! realm.write(needTransition) {[unowned self] in
                      realm.add(self)
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>then I store fetched records in Array </p>
  
  <pre><code>let userInput = "input somthing"
  let phraseList = CKPhraseModel().fetchObjects(userInput)
  for (_,phraseModel) in phraseList.enumerate() {
       candidates.append(phraseModel)
  }
  </code></pre>
  
  <p>Then I want to display <code>candidates</code> information in UI when the user clicks one of these.  I will call CKPhraseModel's <code>save</code> function to save changes. This step is on main thread.</p>