Java Collection performance question
- by Shervin
I have created a method that takes two Collection<String> as input and copies one to the other.
However, I am not sure if I should check if the collections contain the same elements before I start copying, or if I should just copy regardless. This is the method:
/**
* Copies from one collection to the other. Does not allow empty string.
* Removes duplicates.
* Clears the too Collection first
* @param target
* @param dest
*/
public static void copyStringCollectionAndRemoveDuplicates(Collection<String> target, Collection<String> dest) {
if(target == null || dest == null)
return;
//Is this faster to do? Or should I just comment this block out
if(target.containsAll(dest))
return;
dest.clear();
Set<String> uniqueSet = new LinkedHashSet<String>(target.size());
for(String f : target)
if(!"".equals(f))
uniqueSet.add(f);
dest.addAll(uniqueSet);
}
Maybe it is faster to just remove the
if(target.containsAll(dest))
return;
Because this method will iterate over the entire collection anyways.