使用NSPredicate和block过滤Realm之间的区别 [英] Differences between filtering Realm with NSPredicate and block

查看:115
本文介绍了使用NSPredicate和block过滤Realm之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Realm的查询性能.给出以下代码:

I'm wondering about Realm's query performance. Given this code:

let result1 = realm.objects(Person.self).filter("age < 30 AND ... AND ...")
let result2 = realm.objects(Person.self).filter({ $0.age < 30 }).filter({$0.name .... }).filter({$0.nickname ...})

result1是通过使用NSPredicate过滤Person对象来创建的,而result2是使用Swift的集合类型中的filter方法进行过滤的.

result1 is created by filtering Person objects using an NSPredicate, while result2 is filtering using the filter method from Swift's collection types.

这两种过滤方法之间是否存在性能差异?

Is there a performance difference between these two approaches to filtering?

推荐答案

是的,两种方法之间存在性能差异.

Yes, there is a performance difference between the two approaches.

基于NSPredicate的筛选由Realm的查询引擎执行,该引擎直接对Realm文件中的数据进行筛选,而无需创建Person的实例.它可以利用数据库结构的知识来更有效地执行查询(例如,通过使用索引).相比之下,基于块的过滤必须为Realm中的每个对象创建Person的实例,以将它们传递给块.

The NSPredicate-based filtering is performed by Realm's query engine, which filters directly on the data in the Realm file without ever creating instances of Person. It can take advantage of knowledge of the database structure to perform the queries more efficiently (by using indexes, for instance). In contrast, the block based filtering must create instances of Person for each object in your Realm in order to pass them to the block.

还有其他语义差异,这主要是由于两种方法的结果类型不同.基于NSPredicate的过滤返回的是Results<T>而不是基于块的过滤返回的[T].

There are other semantic differences as well, which primarily stem from the differing result types of the two methods. The NSPredicate-based filtering returns a Results<T> rather than the [T] that the block-based filtering returns.

Results<T>是查询结果的实时更新视图.您可以将一个交给视图控制器,并且在应用程序的其他部分执行导致新对象开始与谓词匹配的写操作之后,其内容将更新.您还可以注册变更通知,以了解新对象何时开始与谓词匹配,现有对象停止与谓词匹配或匹配的对象何时以某种方式被修改.

Results<T> is a live-updating view onto the results of your query. You can hand one to a view controller and its contents will update after other parts of your application perform writes that cause new objects to begin matching the predicate. You can also register for change notifications to learn about when new objects begin matching the predicate, an existing object stops matching it, or when an object that matches was modified in some way.

这篇关于使用NSPredicate和block过滤Realm之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆