Java Collection performance question

Posted by Shervin on Stack Overflow See other posts from Stack Overflow or by Shervin
Published on 2010-05-27T07:59:28Z Indexed on 2010/05/27 8:01 UTC
Read the original article Hit count: 257

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about Performance