【问题标题】:objectForPrimaryKey vs filtered query(to match primary key) performance, which one is faster for large data?objectForPrimaryKey 与过滤查询(匹配主键)性能,哪个对大数据更快?
【发布时间】:2021-03-19 10:25:05
【问题描述】:

这里我举个例子

class TestRealm {
    constructor(realmDB) {
        this.realmDB = realmDB;
        this.allRealm = this.realmDB.objects('Person');
    }

    query1(primary_key) {
        try {
            const response = this.allRealm.filtered(`_id == "${primary_key}"`);
            if (response.length === 0) {
                console.log('unable to find');
                return;
            }
            return response.toJSON()[0];
        }
        catch (e) {
            console.log(e);
        }
    }

    query2(primary_key) {
        try {
            const response = this.realmDB.objectForPrimaryKey('Person', `"${primary_key}"`);
            if (!response) {
                console.log('unable to find');
                return;
            }
            return response.toJSON();
        }
        catch (e) {
            console.log(e);
        }
    }
}

假设打开领域后,我将领域对象传递给 TestRealm 构造函数。在这种情况下,哪种查询对大数据有效?

【问题讨论】:

    标签: javascript react-native realm realm-js


    【解决方案1】:

    让我们从排列术语开始

    这是一个查询(又名过滤器),将返回一个领域结果对象

    const response = this.allRealm.filtered(`_id == "${primary_key}"`);
            
    

    不是查询,将返回该特定对象

    const response = this.realmDB.objectForPrimaryKey('Person', `"${primary_key}"`);
    

    所以你返回了两个不同的东西——第一个例子中的response 是一个实时更新的领域结果对象,所以它比返回对象本身有更多的开销。

    另请注意,对于“大数据”,第二个选项基本上不受数据集大小的影响(一般而言)

    第二个例子要快得多。

    【讨论】:

    • 嗨杰,谢谢你的回复,但我有疑问....在第一个响应中,我将获得只有一个领域对象的领域结果对象(因为 primary_key 是唯一的),在第二个响应中我'将只获得一个领域对象。所以我的问题是对于大数据,哪个更快(object.filtered 或 objectForPrimaryKey)?注意:在两个查询中,我都在转换为 JSON() 后返回,因此返回的对象不再是实时对象。
    • @PrahladSinghNegi 第一个例子可以返回很多对象;过滤器不知道它的过滤内容,它只会返回与过滤器匹配的所有对象。而第二个示例将永远返回一个特定对象。如答案中所述,第二个示例“快得多”,数据集的大小不会影响其性能。我们对此进行了大量测试,因为我们的数据集通常为 2Gb 或更大。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多