Java集合性能调优
初始化优化
容量规划
public class CollectionCapacityExample {
public void badInitialization() {
List<String> list = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
list.add("item" + i);
}
Map<String, String> map = new HashMap<>();
for (int i = 0; i < 1000; i++) {
map.put("key" + i, "value" + i);
}
}
public void goodInitialization() {
List<String> list = new ArrayList<>(1000);
for (int i = 0; i < 1000; i++) {
list.add("item" + i);
}
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);
}
}
}
批量操作
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() {
List<String> arrayList = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
arrayList.add("item" + i);
}
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() {
List<String> linkedList = new LinkedList<>();
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);
for (int i = 0; i < list.size(); i++) {
}
LinkedList<String> linkedList = new LinkedList<>();
for (int i = 0; i < linkedList.size(); i++) {
linkedList.get(i);
}
}
public void goodIteration() {
List<String> list = new ArrayList<>(10000);
int size = list.size();
for (int i = 0; i < size; i++) {
}
LinkedList<String> linkedList = new LinkedList<>();
for (String item : linkedList) {
}
list.forEach(item -> {
});
}
}
并发优化
选择合适的并发集合
public class ConcurrentCollectionExample {
public void concurrentRead() {
Map<String, String> concurrentMap = new ConcurrentHashMap<>();
Map<String, String> synchronizedMap =
Collections.synchronizedMap(new HashMap<>());
int threadCount = 10;
int operationsPerThread = 100000;
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");
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() {
List<String> copyOnWriteList = new CopyOnWriteArrayList<>();
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 bitSet = new BitSet(1000000);
list.clear();
System.gc();
}
}
对象池化
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) {
int size = 100000;
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");
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");
}
}