Sorting Remarks
Home
Introduction
Philosophy
General techniques
Sorting
Searching
Factory
Persistence
Logging
Streaming
Tokenizers
Parsing
File Searching
Command
PseudoPatterns
Compiling
Downloads
FeedBack

This section contains some remarks about the sorting component.

IComparable

There are several ways to define sorting criteria. Comparers are but one of them. Another option would be to have the elements in the container implement a special interface. Using this interface you can then ask the object itself to compare itself with another value. The word is that this is more Object-Oriented. Before we start with a list of pros and cons, here is the definition of the interface :

interface iComparable
Public Function CompareTo(ByVal anOtherValue As Object) As Long
End Function

Carefully inspect the interface to see the first weak point : the anotherValue parameter is an object, not a variant. The reason for this is verbose but simple : Sorting deals with elements of an homogeneous type.  Since you need an object to implement an interface, the second parameter can only be another object.  This means that any method based on IComparable must necessary deal with objects only.

You cannot sort a container on different criteria at different times (I.e. once by name and then by street) The sort order is thus bound to the type of the element. 

What’s worse, you need special parameters to specify ascending/descending order, ... IComparers cannot be configured, decorated or composed.  They are fixed. IComparable doesn't let you combine different search criteria. (You could do it by either wrapping or using state variables outside of the  elements)

You can write an iComparer that is based on the assumption of  IComparable elements.  As a matter of fact, I just did :

Implements iComparer

Private Function iComparer_Compare(ByVal Source As Variant, ByVal Destination As Variant) As Long
  Dim objSource As iComparable
 
  Set objSource = Source
  iComparer_Compare = objSource.CompareTo(Destination)
End Function

So the bottom line is that IComparable is just a special case for comparers.  Therefore you can do everything you do with IComparables with IComparers but not vice-versa.  As another consequence, sorting with iComparables is necessary more performant.  It can make more assumptions because it is less abstract and can therefore gain in speed. (a proof of this was found during the benchmarks)

 

 

 

[BenchMarks]
[
Sorting Remarks]
[
James Barbetti Implementations]

 

Site updated : Monday, February 17, 2003