Better practice to re-instantiate a List or invoke clear()

前端 未结 4 383
执念已碎
执念已碎 2020-12-03 00:53

Using Java (1.6) is it better to call the clear() method on a List or just re-instantiate the reference?

I have an ArrayList that is filled with an unknown number of

4条回答
  •  情深已故
    2020-12-03 01:42

    There is no advantage for list.clear() than new XXList. Here is my investigation to compare performance.

                import java.util.ArrayList;
                import java.util.List;
    
                public class ClearList {
    
    
                    public static void testClear(int m, int n) {
                        List list = new ArrayList<>();
                        long start = System.currentTimeMillis();
    
                        for (int i = 0; i < m; i++) {
                            for (int j = 0; j < n; j++) {
                                list.add(Integer.parseInt("" + j + i));
                            }
                            list.clear();
                        }
    
                        System.out.println(System.currentTimeMillis() - start);
                    }
    
                    public static void testNewInit(int m, int n) {
                        List list = new ArrayList<>();
                        long start = System.currentTimeMillis();
    
                        for (int i = 0; i < m; i++) {
                            for (int j = 0; j < n; j++) {
                                list.add(Integer.parseInt("" + j + i));
                            }
                            list = new ArrayList<>();
                        }
    
                        System.out.println(System.currentTimeMillis() - start);
                    }
    
                    public static void main(String[] args) {
                        System.out.println("clear ArrayList:");
                        testClear(991000, 100);
                        System.out.println("new ArrayList:");
                        testNewInit(991000, 100);
                    }
    
                }
    
    
                /*--*
                 * Out:
                 *
                 * clear ArrayList:
                 * 8391
                 * new ArrayList:
                 * 6871
                */
    

提交回复
热议问题