实体记录的快速计数
我想计算我的模型中每个实体的所有记录,以获取包含的内容的全局概述。
我使用context.Count(用于:请求)
获得全局计数,但是在具有〜400 000记录的实体中执行约10秒。
是否有更快的方法来查询记录的数量?
我想象context.count()
是相当优化的,但是也许它仍然为缓存提供了一些东西,我不需要?
代码:
var counts : [String: Int] = [:]
for entity in self.container.managedObjectModel.entities {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entity.name!)
do {
let count = try mainContext.count(for: request)
counts[entity.name!] = count
} catch {
Logger.error("Couldn't count entity \(entity.name)")
}
}
I'd like to count all records of each entity in my model, to get a global overview of what it contains.
I used context.count(for: request)
to get the global count, but it takes ~10s to execute in an entity with ~400 000 records.
Is there any faster way to query the number of records ?
I imagine context.count()
is fairly optimized, but maybe it still fetches some stuff to the cache, which I don't need ?
Code:
var counts : [String: Int] = [:]
for entity in self.container.managedObjectModel.entities {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entity.name!)
do {
let count = try mainContext.count(for: request)
counts[entity.name!] = count
} catch {
Logger.error("Couldn't count entity \(entity.name)")
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查核心数据调试日志,很明显
count(for:)
被转换为SQL语句从...
中选择计数(*),没有其他方法这要比计算表中的行数(对象)的速度快。而且由于返回的唯一一件事是
int
值,因为使用count(for:)
Checking the Core Data debug logs it is clear that
count(for:)
is translated to the SQL statementSELECT COUNT(*) FROM ...
and there is no other way that is faster than that for counting the number of rows (objects) in a table.And since the only thing returned is an
Int
value nothing gets cached because of usingcount(for:)