I need to verify if a certain user exist on my asp.net site.I want to know if which of these two functions is more efficient, faster and better compared to each other and why.Thanks in advance!
Public Function CheckIfFriendExist(ByVal arg As String) As Boolean
Dim alluser As New MembershipUserCollection()
alluser = Membership.GetAllUsers()
For Each user As MembershipUser In alluser
If user.UserName.ToLower() = arg.ToLower() Then
Return True
Exit For
End If
Next
Return False
End Function
or
Public Function CheckIFFriendExist2(ByVal arg As String) As Boolean
Dim x As Integer = 0
Dim themember As MembershipUserCollection = Membership.FindUsersByName(arg, 0, 1, 1)
For Each member As MembershipUser In themember
x = x + 1
Next
If x > 0 Then
Return True
Else
Return False
End If
End Function
Generally speaking, the second option has the better potential for performance. The actual effect depends on which membership provider you are using, but in the second case any implementation can take advantage of any internal indexing mechanisms if they are present, and potentially less data needs to be retrieved and transferred because you’re only getting at most one
MembershipUserdue to the paging.Theoretically, the first option could be faster than the second, but that would mean the membership provider implementation really sucks 🙂
You appear to be counting the number of members in the collection, but you merely need to know if there is at least one member in the collection. Thus counting is not actually necessary. Also, what is wrong with using the
Countproperty? I’m not saying this for optimization purposes since the impact will be minimal, but I think the intent of your code would be clearer if written that way.Alternatively, use
Membership.GetUserto retrieve a single user by name. After all, I wouldn’t recommend implementing a membership provider that allows for multiple users with the same name.