实体记录的快速计数

发布于 2025-02-07 03:55:26 字数 650 浏览 1 评论 0原文

我想计算我的模型中每个实体的所有记录,以获取包含的内容的全局概述。

我使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抚你发端 2025-02-14 03:55:26

检查核心数据调试日志,很明显count(for:)被转换为SQL语句从...中选择计数(*),没有其他方法这要比计算表中的行数(对象)的速度快。

而且由于返回的唯一一件事是int值,因为使用count(for:)

Checking the Core Data debug logs it is clear that count(for:) is translated to the SQL statement SELECT 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 using count(for:)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文