Wednesday, April 13, 2011

Which is faster, contains() or indexOf() in a List?

One of the small things I was trying to solve today had to do with figuring out if something is not a member of a list. The list can be arbitrarily long and I need an efficient way of getting the data.

My first attempt to write that was something like:

public static boolean isNotMemberOf( Object type, List invalidTypes) {
return (invalidTypes.indexOf(type) == -1);
}

This makes for ugly reading though. My next attempt was to use the contains method

public static boolean isNotMemberOf( Object type, List invalidTypes) {
return (!invalidTypes.contains(type));
} 

Internally, contains apparently uses the indexOf call. So the question then becomes, which one is faster and what should I do? Should I just use contains for easier readability (and fewer WTFs a month later on, when someone else sees it)?

No comments: