Why does Java's ArrayList's remove function seem to cost so little?

前端 未结 5 987
情书的邮戳
情书的邮戳 2020-12-07 12:52

I have a function which manipulates a very large list, exceeding about 250,000 items. For the majority of those items, it simply replaces the item at position x. However, fo

5条回答
  •  盖世英雄少女心
    2020-12-07 13:02

    Array copy is a rather unexpensive operation. It is done on a very basic level (its a java native static method) and you are not yet in the range where the performance becomes really important.

    In your example you copy approx 12000 times an array of size 150000 (on average). This does not take much time. I tested it here on my laptop and it took less than 500 ms.

    Update I used the following code to measure on my laptop (Intel P8400)

    import java.util.Random;
    
    public class PerformanceArrayCopy {
    
        public static void main(String[] args) {
    
            int[] lengths = new int[] { 10000, 50000, 125000, 250000 };
            int[] loops = new int[] { 1000, 5000, 10000, 20000 };
    
            for (int length : lengths) {
                for (int loop : loops) {
    
                    Object[] list1 = new Object[length];
                    Object[] list2 = new Object[length];
    
                    for (int k = 0; k < 100; k++) {
                        System.arraycopy(list1, 0, list2, 0, list1.length);
                    }
    
                    int[] len = new int[loop];
                    int[] ofs = new int[loop];
    
                    Random rnd = new Random();
                    for (int k = 0; k < loop; k++) {
                        len[k] = rnd.nextInt(length);
                        ofs[k] = rnd.nextInt(length - len[k]);
                    }
    
                    long n = System.nanoTime();
                    for (int k = 0; k < loop; k++) {
                        System.arraycopy(list1, ofs[k], list2, ofs[k], len[k]);
                    }
                    n = System.nanoTime() - n;
                    System.out.print("length: " + length);
                    System.out.print("\tloop: " + loop);
                    System.out.print("\truntime [ms]: " + n / 1000000);
                    System.out.println();
                }
            }
        }
    }
    

    Some results:

    length: 10000   loop: 10000 runtime [ms]: 47
    length: 50000   loop: 10000 runtime [ms]: 228
    length: 125000  loop: 10000 runtime [ms]: 575
    length: 250000  loop: 10000 runtime [ms]: 1198
    

提交回复
热议问题