简体   繁体   English

Realm-JS:在排序结果列表中查找元素索引的高效方法

[英]Realm-JS: Performant way to find the index of an element in sorted results list

I am searching for a perfomant way to find the index of a given realm-object in a sorted results list.我正在寻找一种在排序结果列表中查找给定领域对象索引的高性能方法。 I am aware of this similar question, which was answered with using indexOf , so my current solution looks like this:我知道这个类似的问题,使用indexOf回答了这个问题,所以我当前的解决方案如下所示:

const sortedRecords = realm.objects('mySchema').sorted('time', true) // 'time' property is a timestamp

// grab element of interest by id (e.g. 123)
const item = realm.objectForPrimaryKey('mySchema','123')

// find index of that object in my sorted results list
const index = sortedRecords.indexOf(item)

My basic concern here is performance for lager datasets.我在这里的基本关注是更大数据集的性能。 Is the indexOf implementation of a realm-list improved for this in any way, or is it the same as from a JavaScript array?领域列表的indexOf实现是否以任何方式改进,还是与 JavaScript 阵列相同? I know there is the possibility to create indexed properties , would indexing the time property improve the performance in this case?我知道有可能创建索引属性,在这种情况下索引time属性会提高性能吗?

Note: In the realm-js api documentation, the indexOf section does not reference to Array.prototype.indexOf , as other sections do.注意:在 realm-js api 文档中, indexOf 部分不像其他部分那样引用Array.prototype.indexOf This made me optimistic it's an own implementation, but it's not stated clearly.这让我很乐观,它是一个自己的实现,但没有明确说明。

Realm query methods return a Results object which is quite different from an Array object, the main difference is that the first one can change over time even without calling methods on it: adding and/or deleting record to the source schema can result in a change to Results object. Realm 查询方法返回Results object 这与Array object 完全不同,主要区别在于第一个即使不调用方法也可以随时间变化:添加和/或删除源记录到 a Results object。

The only common thing between Results.indexOf and Array.indexOf is the name of the method. Results.indexOfArray.indexOf之间唯一的共同点是方法的名称。

Once said that is easy to also say that it makes no sense to compare the efficiency of the two methods.说起来容易,也说比较两种方法的效率是没有意义的。

In general, a problem common to all indexOf implementations is that they need a sequential scan and in the worst case (ie the not found case) a full scan is required.一般来说,所有indexOf实现的共同问题是它们需要顺序扫描,并且在最坏的情况下(即未找到的情况)需要完全扫描。 The wort implemented indexOf executed against 10 elements has no impact on program performances while the best implemented indexOf executed against 1M elements can have a severe impact on program performances.针对 10 个元素执行的麦汁实现indexOf对程序性能没有影响,而针对 1M 个元素执行的最佳实现indexOf可能对程序性能产生严重影响。 When possible it's always a good idea avoiding to use indexOf on large amounts of data.如果可能,避免在大量数据上使用indexOf总是一个好主意。

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM