Redis: Is ZADD better than O(logN) when the inserted element is at the beginning or end?

半腔热情 提交于 2019-11-30 18:30:50

问题


The redis documentation for ZADD states the operation is O(log N).

However, does anyone know if ZADD is better than O(log N) when the inserted element is at the beginning or end of the sort order?

E.g. for certain implementations this could be O(1).

Specifically, the redis tutorial states that:

Sorted sets are implemented via a dual-ported data structure containing both a skip list and an hash table, so every time we add an element Redis performs an O(log(N)) operation.

It seems plausible to modify a skip list to support O(k) insert at beginning and end, where k is the max level of the skip list.


回答1:


I had cross-posted this question on the Redis website, and Pieter Noordhuis provided an answer there, which I am cross-posting here:


That is correct. The sorted set relies on an RNG to determine the number of levels per node (it's a probabilistic data structure). Inserting/deleting an element at the beginning of the skiplist can be O(1), while the theoretical worst case performance is O(N) (with every node having the same level). However, the amortized time complexity is O(log N) when you take in account the distribution of the levels among the nodes.




回答2:


Is there a relationship between k and log(N)? If they're related by a constant factor, you've not actually changed anything. (I don't know if that relationship exists, but it looks highly plausible given that the wikipedia page on the topic has apparently that relationship in the layer construction. OTOH, the page doesn't link to a proof and I don't feel like deriving it by hand right now, so this can only be conjecture.)

Also, in general the fact that the algorithm overall is O(log N) doesn't stop particular special cases from being better (e.g., O(1)).



来源:https://stackoverflow.com/questions/7140527/redis-is-zadd-better-than-ologn-when-the-inserted-element-is-at-the-beginning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!