Java集合性能调优

Java集合性能调优

初始化优化

容量规划

public class CollectionCapacityExample {
    // 不好的实践:使用默认容量
    public void badInitialization() {
        List<String> list = new ArrayList<>();  // 默认容量10
        for (int i = 0; i < 1000; i++) {
            list.add("item" + i);  // 多次扩容
        }
        
        Map<String, String> map = new HashMap<>();  // 默认容量16
        for (int i = 0; i < 1000; i++) {
            map.put("key" + i, "value" + i);  // 多次扩容
        }
    }
    
    // 好的实践:预估容量
    public void goodInitialization() {
        // 预设ArrayList容量
        List<String> list = new ArrayList<>(1000);
        for (int i = 0; i < 1000; i++) {
            list.add("item" + i);  // 只扩容一次
        }
        
        // 预设HashMap容量
        int expectedSize = 1000;
        Map<String, String> map = new HashMap<>(
            (int)(expectedSize / 0.75f) + 1  // 考虑负载因子
        );
        for (int i = 0; i < expectedSize; i++) {
            map.put("key" + i, "value" + i);  // 无需扩容
        }
    }
    
    // 容量计算工具
    public static class CapacityUtil {
        public static int getHashMapCapacity(int expectedSize) {
            return (int)(expectedSize / 0.75f) + 1;
        }
        
        public static int getArrayListCapacity(int expectedSize) {
            return (int)(expectedSize * 1.1f);  // 预留10%空间
        }
    }
}

批量操作

public class BatchOperationExample {
    // 不好的实践:逐个操作
    public void badBatchOperation() {
        List<String> list = new ArrayList<>(1000);
        
        // 逐个添加
        for (int i = 0; i < 1000; i++) {
            list.add("item" + i);
        }
        
        // 逐个删除
        for (String item : new ArrayList<>(list)) {
            if (item.startsWith("item5")) {
                list.remove(item);
            }
        }
    }
    
    // 好的实践:批量操作
    public void goodBatchOperation() {
        // 批量添加
        List<String> items = new ArrayList<>(1000);
        for (int i = 0; i < 1000; i++) {
            items.add("item" + i);
        }
        
        List<String> list = new ArrayList<>(items);  // 一次性添加
        
        // 批量删除
        list.removeIf(item -> item.startsWith("item5"));
    }
    
    // 流式操作
    public void streamOperation() {
        List<String> list = new ArrayList<>(1000);
        
        // 并行处理
        list.parallelStream()
            .filter(item -> item.startsWith("item"))
            .map(String::toUpperCase)
            .collect(Collectors.toList());
    }
}

访问优化

选择合适的集合类型

public class CollectionSelectionExample {
    // 随机访问场景
    public void randomAccess() {
        // 好的选择:ArrayList
        List<String> arrayList = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            arrayList.add("item" + i);
        }
        
        // 不好的选择:LinkedList
        List<String> linkedList = new LinkedList<>();
        for (int i = 0; i < 10000; i++) {
            linkedList.add("item" + i);
        }
        
        // 性能对比
        long start = System.nanoTime();
        for (int i = 0; i < 10000; i++) {
            arrayList.get(i);
        }
        System.out.println("ArrayList访问时间: " + 
            (System.nanoTime() - start) / 1000000 + "ms");
        
        start = System.nanoTime();
        for (int i = 0; i < 10000; i++) {
            linkedList.get(i);
        }
        System.out.println("LinkedList访问时间: " + 
            (System.nanoTime() - start) / 1000000 + "ms");
    }
    
    // 频繁插入删除场景
    public void frequentModification() {
        // 好的选择:LinkedList
        List<String> linkedList = new LinkedList<>();
        
        // 不好的选择:ArrayList
        List<String> arrayList = new ArrayList<>();
        
        // 性能对比
        long start = System.nanoTime();
        for (int i = 0; i < 10000; i++) {
            linkedList.add(0, "item" + i);
        }
        System.out.println("LinkedList插入时间: " + 
            (System.nanoTime() - start) / 1000000 + "ms");
        
        start = System.nanoTime();
        for (int i = 0; i < 10000; i++) {
            arrayList.add(0, "item" + i);
        }
        System.out.println("ArrayList插入时间: " + 
            (System.nanoTime() - start) / 1000000 + "ms");
    }
}

遍历优化

public class IterationOptimizationExample {
    // 不好的实践:低效遍历
    public void badIteration() {
        List<String> list = new ArrayList<>(10000);
        
        // 重复获取size
        for (int i = 0; i < list.size(); i++) {
            // 处理元素
        }
        
        // 使用get遍历LinkedList
        LinkedList<String> linkedList = new LinkedList<>();
        for (int i = 0; i < linkedList.size(); i++) {
            linkedList.get(i);  // O(n)复杂度
        }
    }
    
    // 好的实践:高效遍历
    public void goodIteration() {
        List<String> list = new ArrayList<>(10000);
        
        // 缓存size
        int size = list.size();
        for (int i = 0; i < size; i++) {
            // 处理元素
        }
        
        // 使用迭代器遍历LinkedList
        LinkedList<String> linkedList = new LinkedList<>();
        for (String item : linkedList) {  // O(1)复杂度
            // 处理元素
        }
        
        // 使用forEach方法
        list.forEach(item -> {
            // 处理元素
        });
    }
}

并发优化

选择合适的并发集合

public class ConcurrentCollectionExample {
    // 高并发读取场景
    public void concurrentRead() {
        // 好的选择:ConcurrentHashMap
        Map<String, String> concurrentMap = new ConcurrentHashMap<>();
        
        // 不好的选择:同步的HashMap
        Map<String, String> synchronizedMap = 
            Collections.synchronizedMap(new HashMap<>());
            
        // 性能对比
        int threadCount = 10;
        int operationsPerThread = 100000;
        
        // 测试ConcurrentHashMap
        long start = System.nanoTime();
        Thread[] threads1 = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++) {
            threads1[i] = new Thread(() -> {
                for (int j = 0; j < operationsPerThread; j++) {
                    concurrentMap.get("key");
                }
            });
            threads1[i].start();
        }
        
        // 等待所有线程完成
        for (Thread thread : threads1) {
            thread.join();
        }
        System.out.println("ConcurrentHashMap读取时间: " + 
            (System.nanoTime() - start) / 1000000 + "ms");
        
        // 测试同步Map
        start = System.nanoTime();
        Thread[] threads2 = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++) {
            threads2[i] = new Thread(() -> {
                for (int j = 0; j < operationsPerThread; j++) {
                    synchronizedMap.get("key");
                }
            });
            threads2[i].start();
        }
        
        // 等待所有线程完成
        for (Thread thread : threads2) {
            thread.join();
        }
        System.out.println("SynchronizedMap读取时间: " + 
            (System.nanoTime() - start) / 1000000 + "ms");
    }
    
    // 读多写少场景
    public void readMostlyScenario() {
        // 好的选择:CopyOnWriteArrayList
        List<String> copyOnWriteList = new CopyOnWriteArrayList<>();
        
        // 不好的选择:同步的ArrayList
        List<String> synchronizedList = 
            Collections.synchronizedList(new ArrayList<>());
    }
}

分段锁优化

public class SegmentLockExample {
    public class SegmentedHashMap<K, V> {
        private static final int SEGMENTS = 16;
        private final Map<K, V>[] segments;
        private final ReentrantLock[] locks;
        
        @SuppressWarnings("unchecked")
        public SegmentedHashMap() {
            segments = new HashMap[SEGMENTS];
            locks = new ReentrantLock[SEGMENTS];
            for (int i = 0; i < SEGMENTS; i++) {
                segments[i] = new HashMap<>();
                locks[i] = new ReentrantLock();
            }
        }
        
        private int getSegment(K key) {
            return Math.abs(key.hashCode() % SEGMENTS);
        }
        
        public V put(K key, V value) {
            int segment = getSegment(key);
            locks[segment].lock();
            try {
                return segments[segment].put(key, value);
            } finally {
                locks[segment].unlock();
            }
        }
        
        public V get(K key) {
            int segment = getSegment(key);
            locks[segment].lock();
            try {
                return segments[segment].get(key);
            } finally {
                locks[segment].unlock();
            }
        }
    }
}

内存优化

减少内存占用

public class MemoryOptimizationExample {
    // 不好的实践:内存浪费
    public void memoryWaste() {
        // 使用过大的初始容量
        List<String> list = new ArrayList<>(1000000);  // 预分配大量内存
        
        // 使用包装类型
        List<Integer> integers = new ArrayList<>();
        for (int i = 0; i < 1000000; i++) {
            integers.add(i);  // 每个整数都需要包装
        }
    }
    
    // 好的实践:内存优化
    public void memoryOptimization() {
        // 使用合适的初始容量
        List<String> list = new ArrayList<>(1000);
        
        // 使用基本类型数组
        int[] array = new int[1000000];  // 直接存储整数
        
        // 使用BitSet代替boolean数组
        BitSet bitSet = new BitSet(1000000);  // 每个boolean只占1位
        
        // 及时清理不用的引用
        list.clear();
        System.gc();  // 提示JVM进行垃圾回收
    }
}

对象池化

public class ObjectPoolExample {
    public class StringPool {
        private final Map<String, WeakReference<String>> pool = 
            new ConcurrentHashMap<>();
        
        public String intern(String str) {
            WeakReference<String> ref = pool.get(str);
            String cached = (ref != null) ? ref.get() : null;
            if (cached != null) {
                return cached;
            }
            
            pool.put(str, new WeakReference<>(str));
            return str;
        }
    }
    
    public class ObjectPool<T> {
        private final Queue<T> pool;
        private final Supplier<T> factory;
        private final int maxSize;
        
        public ObjectPool(Supplier<T> factory, int maxSize) {
            this.factory = factory;
            this.maxSize = maxSize;
            this.pool = new ConcurrentLinkedQueue<>();
        }
        
        public T borrow() {
            T obj = pool.poll();
            return (obj != null) ? obj : factory.get();
        }
        
        public void release(T obj) {
            if (pool.size() < maxSize) {
                pool.offer(obj);
            }
        }
    }
}

实际应用

性能监控

public class CollectionMonitorExample {
    public class MonitoredList<E> extends ArrayList<E> {
        private final AtomicLong addCount = new AtomicLong();
        private final AtomicLong removeCount = new AtomicLong();
        private final AtomicLong accessCount = new AtomicLong();
        
        @Override
        public boolean add(E e) {
            addCount.incrementAndGet();
            return super.add(e);
        }
        
        @Override
        public E remove(int index) {
            removeCount.incrementAndGet();
            return super.remove(index);
        }
        
        @Override
        public E get(int index) {
            accessCount.incrementAndGet();
            return super.get(index);
        }
        
        public void printStats() {
            System.out.println("Add operations: " + addCount.get());
            System.out.println("Remove operations: " + removeCount.get());
            System.out.println("Access operations: " + accessCount.get());
        }
    }
}

性能测试

public class CollectionPerformanceTest {
    public static void main(String[] args) {
        // 测试不同List实现的性能
        int size = 100000;
        
        // ArrayList测试
        List<Integer> arrayList = new ArrayList<>();
        long start = System.nanoTime();
        for (int i = 0; i < size; i++) {
            arrayList.add(i);
        }
        System.out.println("ArrayList添加时间: " + 
            (System.nanoTime() - start) / 1000000 + "ms");
        
        // LinkedList测试
        List<Integer> linkedList = new LinkedList<>();
        start = System.nanoTime();
        for (int i = 0; i < size; i++) {
            linkedList.add(i);
        }
        System.out.println("LinkedList添加时间: " + 
            (System.nanoTime() - start) / 1000000 + "ms");
        
        // 随机访问测试
        start = System.nanoTime();
        for (int i = 0; i < size; i++) {
            arrayList.get(i);
        }
        System.out.println("ArrayList访问时间: " + 
            (System.nanoTime() - start) / 1000000 + "ms");
        
        start = System.nanoTime();
        for (int i = 0; i < size; i++) {
            linkedList.get(i);
        }
        System.out.println("LinkedList访问时间: " + 
            (System.nanoTime() - start) / 1000000 + "ms");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值