Question which sort is more efficient

jrbilodeau

Member
Joined
Apr 29, 2009
Messages
7
Programming Experience
1-3
just wondering which of these two sort methods would be more efficient

VB.NET:
 movies.OrderBy(Function(m As Movie) m.Title)

or

VB.NET:
movies.Sort()

movies is a list(of Movie)

VB.NET:
Public Class Movie
    Implements IComparable

    'Member variables
    Public WindowsMovieFilename As String
    Public PBOMovieFilename As String
    Public MovieSheet As String
    Public CoverArt As String
    Public Nfo As String
    Public Title As String
    Public Genres As List(Of String)


    Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo

        If TypeOf obj Is Movie Then
            Dim temp As Movie = CType(obj, Movie)
            Return Title.CompareTo(temp.Title)
        Else
            Throw New Exception("Invalid object type")
        End If

    End Function

End Class

thanks
 
It's not really which is more efficient that matters here. They do two different things. The first one returns a new IEnumerable(Of Movie) in the specified order without making any change to the original List, while the second actually sorts the List itself. It depends on which of those you want.

Also, the first option doesn't rely on the IComparable implementation in the Movie class while the second does. The first option would allow you to specify a different property and order the items a different way.

Thyat said, the first option COULD make use of the inbuilt functionality of the class if it also implemented IComparable(Of Movie), which it should. When there's a standard and generic form of an interface, you should pretty much always implement both:
Public Class Movie
    Implements IComparable, IComparable(Of Movie)

    'Member variables
    Public WindowsMovieFilename As String
    Public PBOMovieFilename As String
    Public MovieSheet As String
    Public CoverArt As String
    Public Nfo As String
    Public Title As String
    Public Genres As List(Of String)


    Public Function CompareTo(ByVal obj As Object) As Integer Implements IComparable.CompareTo
        Return CompareTo(DirectCast(obj, Movie))
    End Function

    Public Function CompareTo(ByVal other As Movie) As Integer Implements IComparable(Of Movie).CompareTo
        Return Me.Title.CompareTo(other.Title)
    End Function

End Class
Your first option could now be:
VB.NET:
movies.OrderBy(Function(m) m)
and the IComparable(Of Movie) implementation will be used.
 
Back
Top