Based on the full amount of the initial performance of two sets performance comparison analysis

Background: The recently encountered a demand for the project, whether the data need to compare two large collection of the same. (Under normal circumstances equal, but starting out code analysis)

Analysis: For such problems, a first idea is that, compared to the size of the two sets, each set further comparison loop element. The second idea is, to see List source, whether from the API, using conventional methods in combination, achieve the same effect.

Based on an idea, here, directly on the code, and lists takes time.

    public static void main(String[] args) {
        List<String> listA = new ArrayList<>();
        List<String> listB = new ArrayList<>();
        for (int i = 0; i < 50000000; i++) {
            listA.add("A");
            listB.add("A");
        }
        long startTime = System.currentTimeMillis();
        if(listA.size()==listB.size()){
            for (int i = 0; i < listA.size(); i++) {
                if(listA.get(i).equals(listB.get(i))){
                    continue;
                }
            }
            long endTime = System.currentTimeMillis();
            System.out.println("比较时间"+(endTime-startTime));
        }
    }

Test six times, times are: 55,54,56,59,55,57.

If the above code (i <90000000), time are: 92,91,91,93,91,92.


 

Based on the second approach, we intend to adopt containsAll method: listA.containsAll (listB) && listB.containsAll (listA)

    public static void main(String[] args) {
        List<String> listA = new ArrayList<>();
        List<String> listB = new ArrayList<>();
        for (int i = 0; i < 50000000; i++) {
            listA.add("A");
            listB.add("A");
        }
        long startTime = System.currentTimeMillis();
        if (listA.containsAll(listB) && listB.containsAll(listA)) {
            long endTime =System.currentTimeMillis (); 
            System.out.println ( "comparison time" + (endTime - the startTime)); 
        } 
    }

Test six times, times are: 119,128,120,120,130,119.

If the above code (i <90000000), are time: 206,213,204,203,205,203.

To sum up: due to less sample, the number of tests, but more. But the basic can be concluded that the advantages and disadvantages of the two methods:

The first cycle for high efficiency, large amount of code.

The second low efficiency, easier to understand, smaller amount of code.

 

Guess you like

Origin www.cnblogs.com/gzhcsu/p/11297001.html