java 集合查找效率 List Set

阅读更多
public class TestListSet {

    private static String LABEL = "testlistset";

    public static void main(String[] args) {

        List list = getList();
        Set set = getSet();
        String tt = LABEL + 83445;
        long tt0 = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            list.contains(tt);
        }
        long tt1 = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            set.contains(tt);
        }
        long tt2 = System.currentTimeMillis();
        System.out.println(String.format("compare list(%d) vs set(%d) ", (tt1 - tt0), (tt2 - tt1)));
    }

    /**
     * @Title: getSet
     * @Description: TODO
     * @return
     */
    private static Set getSet() {
        long t0 = System.currentTimeMillis();
        Set set = new HashSet<>();
        for (int i = 0; i < 100000; i++) {
            set.add(LABEL + i);
        }
        long t1 = System.currentTimeMillis();
        System.out.println("init set 10W times = " + (t1 - t0));
        return set;
    }

    /**
     * @Title: getList
     * @Description: TODO
     * @return
     */
    private static List getList() {
        long t0 = System.currentTimeMillis();
        List list = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            list.add(LABEL + i);
        }
        long t1 = System.currentTimeMillis();
        System.out.println("init list 10W times = " + (t1 - t0));
        return list;
    }

}

结果

init list 10W times = 23
init set 10W times = 50
compare list(70529) vs set(4)

说明
List中contains():调用indexOf(o)方法 遍历List中的每个元素,每个元素与比较对象进行equals()比较,只要有一个相同,就返回true 意思是说他就是会扫描整个List
Set中的contain():调用的是map.containKey(o),内部使用的是Hashtable
/**
     * Returns true if this map contains a mapping for the
     * specified key.
     *
     * @param   key   The key whose presence in this map is to be tested
     * @return true if this map contains a mapping for the specified
     * key.
     */
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }


所以如果在大队列中嵌套循环中比较存在的话,请选用hashset,效率会大大提升。

你可能感兴趣的:(java,结合,list,set,contains,查询效率)