Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are ConcurrentSkipListSet ascending Iterators 'faster' than descending ones?

I’m using the descendingIterator method on ConcurrentSkipListSet. I’ve just checked the documentation and noticed the following comment:

‘Ascending ordered views and their iterators are faster than descending ones.’

See https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentSkipListSet.html#descendingIterator--

Unfortunately it doesn’t provide any more information on this. What kind of performance difference is there? is it significant? and why is there a performance difference?

like image 788
GoldenJam Avatar asked Jun 07 '18 10:06

GoldenJam


People also ask

What is ConcurrentSkipListSet?

public ConcurrentSkipListSet(SortedSet<E> s) Constructs a new set containing the same elements and using the same ordering as the specified sorted set.

What is concurrent skip list?

The ConcurrentSkipListSet class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractSet class. It provides a scalable and concurrent version of NavigableSet in Java.


1 Answers

If you look at the Wikipedia page for Skip Lists you will see that they are effectively a complicated form of linked list with the links going in the direction of an ordering of the list entries. (The diagram illustrates this clearly ...)

When you traverse the skip list in the forward direction, you are simply following the links. Each next() call is an O(1) operation.

When you traverse the skip list in the reverse direction, each next() call has to find the key before the last key returned. This is an O(logN) operation.

(However, traversing a skip list backwards is still substantially faster than traversing a singly linked list backwards. That would be O(N) for each next() call ...)

If you look under the hood, you will see that a ConcurrentSkipListSet is actually a wrapper for a ConcurrentSkipListMap. In that class, the Node objects in the skip list representation of the map form singly linked chains ... in the ascending key direction. It follows (from the previous) that ascending iteration is faster than descending iteration.

The performance difference will be significant, and it will get more significant as the set size increases because of the O(1) versus O(logN) difference.

like image 144
Stephen C Avatar answered Sep 22 '22 13:09

Stephen C