"数据结构优化就像选择建筑材料,用对了材料,房子更稳固,用错了材料,房子会倒塌!" 🏠💪
🎯 什么是数据结构优化?
想象一下,你是一个超级忙碌的图书管理员 📚。每天都有很多读者来借书还书,如果你把书随便乱放,那找书就会很困难!
数据结构优化就像是选择最合适的书架和整理方式,让找书变得超级简单!
🏃♂️ 核心思想:用合适的数据结构换高效操作,用优化换性能
不合适:查找一本书 → 遍历所有书架 → 找到结果 (耗时:10分钟)
合适: 查找一本书 → 直接定位 → 找到结果 (耗时:10秒)
效率提升:60倍! 🎉
🎨 数据结构优化的四种策略
1. 选择合适的数据结构 - 让工具"匹配"任务 🔧
生活比喻: 就像选择工具,拧螺丝用螺丝刀,切菜用菜刀,用对了工具事半功倍!
@Service
public class DataStructureSelectionService {
// 数组 vs 链表选择
public void demonstrateArrayVsLinkedList() {
// 数组:适合随机访问
int[] array = new int[1000];
for (int i = 0; i < 1000; i++) {
array[i] = i; // O(1) 随机访问
}
// 链表:适合频繁插入删除
LinkedList<Integer> linkedList = new LinkedList<>();
for (int i = 0; i < 1000; i++) {
linkedList.add(i); // O(1) 插入
}
log.info("数组随机访问: {}", array[500]); // O(1)
log.info("链表随机访问: {}", linkedList.get(500)); // O(n)
}
// HashMap vs TreeMap选择
public void demonstrateHashMapVsTreeMap() {
// HashMap:适合快速查找,无序
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 1);
hashMap.put("banana", 2);
hashMap.put("cherry", 3);
// TreeMap:适合有序遍历,自动排序
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("apple", 1);
treeMap.put("banana", 2);
treeMap.put("cherry", 3);
log.info("HashMap查找: {}", hashMap.get("banana")); // O(1)
log.info("TreeMap查找: {}", treeMap.get("banana")); // O(log n)
log.info("TreeMap有序遍历: {}", treeMap.keySet()); // 自动排序
}
// ArrayList vs LinkedList选择
public void demonstrateArrayListVsLinkedList() {
// ArrayList:适合随机访问和末尾操作
List<Integer> arrayList = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
arrayList.add(i); // O(1) 末尾添加
}
// LinkedList:适合频繁插入删除
List<Integer> linkedList = new LinkedList<>();
for (int i = 0; i < 1000; i++) {
linkedList.add(i); // O(1) 插入
}
log.info("ArrayList随机访问: {}", arrayList.get(500)); // O(1)
log.info("LinkedList随机访问: {}", linkedList.get(500)); // O(n)
// 中间插入测试
long start = System.nanoTime();
arrayList.add(500, 999); // O(n)
long end = System.nanoTime();
log.info("ArrayList中间插入耗时: {}ns", end - start);
start = System.nanoTime();
linkedList.add(500, 999); // O(1)
end = System.nanoTime();
log.info("LinkedList中间插入耗时: {}ns", end - start);
}
// HashSet vs TreeSet选择
public void demonstrateHashSetVsTreeSet() {
// HashSet:适合快速查找,无序
Set<String> hashSet = new HashSet<>();
hashSet.add("apple");
hashSet.add("banana");
hashSet.add("cherry");
// TreeSet:适合有序遍历,自动排序
Set<String> treeSet = new TreeSet<>();
treeSet.add("apple");
treeSet.add("banana");
treeSet.add("cherry");
log.info("HashSet查找: {}", hashSet.contains("banana")); // O(1)
log.info("TreeSet查找: {}", treeSet.contains("banana")); // O(log n)
log.info("TreeSet有序遍历: {}", treeSet); // 自动排序
}
// 智能数据结构选择
public <T> Collection<T> selectOptimalDataStructure(List<OperationType> operations, int expectedSize) {
boolean needsOrdering = operations.contains(OperationType.ORDERED_TRAVERSAL);
boolean needsFastLookup = operations.contains(OperationType.FAST_LOOKUP);
boolean needsFrequentInsertion = operations.contains(OperationType.FREQUENT_INSERTION);
boolean needsFrequentDeletion = operations.contains(OperationType.FREQUENT_DELETION);
if (needsOrdering && needsFastLookup) {
return new TreeSet<>(); // 有序且快速查找
} else if (needsFastLookup && !needsOrdering) {
return new HashSet<>(); // 快速查找但无序
} else if (needsFrequentInsertion || needsFrequentDeletion) {
return new LinkedList<>(); // 频繁插入删除
} else {
return new ArrayList<>(); // 默认选择
}
}
private enum OperationType {
ORDERED_TRAVERSAL, FAST_LOOKUP, FREQUENT_INSERTION, FREQUENT_DELETION
}
}
2. 自定义数据结构 - 让结构"量身定制" ✂️
生活比喻: 就像定制衣服,根据身材量身定制,比买现成的更合身!
@Service
public class CustomDataStructureService {
// 自定义LRU缓存
public static class LRUCache<K, V> {
private final int capacity;
private final Map<K, Node<K, V>> cache;
private final Node<K, V> head;
private final Node<K, V> tail;
public LRUCache(int capacity) {
this.capacity = capacity;
this.cache = new HashMap<>();
this.head = new Node<>(null, null);
this.tail = new Node<>(null, null);
head.next = tail;
tail.prev = head;
}
public V get(K key) {
Node<K, V> node = cache.get(key);
if (node != null) {
moveToHead(node);
return node.value;
}
return null;
}
public void put(K key, V value) {
Node<K, V> node = cache.get(key);
if (node != null) {
node.value = value;
moveToHead(node);
} else {
Node<K, V> newNode = new Node<>(key, value);
if (cache.size() >= capacity) {
Node<K, V> tail = popTail();
cache.remove(tail.key);
}
cache.put(key, newNode);
addNode(newNode);
}
}
private void addNode(Node<K, V> node) {
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
private void removeNode(Node<K, V> node) {
Node<K, V> prev = node.prev;
Node<K, V> next = node.next;
prev.next = next;
next.prev = prev;
}
private void moveToHead(Node<K, V> node) {
removeNode(node);
addNode(node);
}
private Node<K, V> popTail() {
Node<K, V> res = tail.prev;
removeNode(res);
return res;
}
private static class Node<K, V> {
K key;
V value;
Node<K, V> prev;
Node<K, V> next;
Node(K key, V value) {
this.key = key;
this.value = value;
}
}
}
// 自定义Trie树
public static class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode current = root;
for (char c : word.toCharArray()) {
if (!current.children.containsKey(c)) {
current.children.put(c, new TrieNode());
}
current = current.children.get(c);
}
current.isEndOfWord = true;
}
public boolean search(String word) {
TrieNode current = root;
for (char c : word.toCharArray()) {
if (!current.children.containsKey(c)) {
return false;
}
current = current.children.get(c);
}
return current.isEndOfWord;
}
public boolean startsWith(String prefix) {
TrieNode current = root;
for (char c : prefix.toCharArray()) {
if (!current.children.containsKey(c)) {
return false;
}
current = current.children.get(c);
}
return true;
}
private static class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
boolean isEndOfWord = false;
}
}
// 自定义优先队列
public static class CustomPriorityQueue<T> {
private final List<T> heap;
private final Comparator<T> comparator;
public CustomPriorityQueue(Comparator<T> comparator) {
this.heap = new ArrayList<>();
this.comparator = comparator;
}
public void offer(T item) {
heap.add(item);
heapifyUp(heap.size() - 1);
}
public T poll() {
if (heap.isEmpty()) {
return null;
}
T root = heap.get(0);
T last = heap.remove(heap.size() - 1);
if (!heap.isEmpty()) {
heap.set(0, last);
heapifyDown(0);
}
return root;
}
public T peek() {
return heap.isEmpty() ? null : heap.get(0);
}
public boolean isEmpty() {
return heap.isEmpty();
}
public int size() {
return heap.size();
}
private void heapifyUp(int index) {
while (index > 0) {
int parentIndex = (index - 1) / 2;
if (comparator.compare(heap.get(index), heap.get(parentIndex)) >= 0) {
break;
}
swap(index, parentIndex);
index = parentIndex;
}
}
private void heapifyDown(int index) {
while (true) {
int leftChild = 2 * index + 1;
int rightChild = 2 * index + 2;
int smallest = index;
if (leftChild < heap.size() &&
comparator.compare(heap.get(leftChild), heap.get(smallest)) < 0) {
smallest = leftChild;
}
if (rightChild < heap.size() &&
comparator.compare(heap.get(rightChild), heap.get(smallest)) < 0) {
smallest = rightChild;
}
if (smallest == index) {
break;
}
swap(index, smallest);
index = smallest;
}
}
private void swap(int i, int j) {
T temp = heap.get(i);
heap.set(i, heap.get(j));
heap.set(j, temp);
}
}
// 自定义环形缓冲区
public static class CircularBuffer<T> {
private final T[] buffer;
private int head;
private int tail;
private int count;
@SuppressWarnings("unchecked")
public CircularBuffer(int capacity) {
this.buffer = (T[]) new Object[capacity];
this.head = 0;
this.tail = 0;
this.count = 0;
}
public boolean offer(T item) {
if (count == buffer.length) {
return false; // 缓冲区已满
}
buffer[tail] = item;
tail = (tail + 1) % buffer.length;
count++;
return true;
}
public T poll() {
if (count == 0) {
return null; // 缓冲区为空
}
T item = buffer[head];
buffer[head] = null; // 帮助GC
head = (head + 1) % buffer.length;
count--;
return item;
}
public T peek() {
return count == 0 ? null : buffer[head];
}
public boolean isEmpty() {
return count == 0;
}
public boolean isFull() {
return count == buffer.length;
}
public int size() {
return count;
}
}
}
3. 位运算优化 - 让操作"飞"起来 🚀
生活比喻: 就像用计算器,按一个键就能完成复杂计算,比手算快多了!
@Service
public class BitwiseOptimizationService {
// 位运算实现快速幂
public long fastPower(long base, long exponent) {
long result = 1;
while (exponent > 0) {
if ((exponent & 1) == 1) {
result *= base;
}
base *= base;
exponent >>= 1;
}
return result;
}
// 位运算实现快速乘法
public long fastMultiply(long a, long b) {
long result = 0;
while (b > 0) {
if ((b & 1) == 1) {
result += a;
}
a <<= 1;
b >>= 1;
}
return result;
}
// 位运算实现快速除法
public long fastDivide(long dividend, long divisor) {
if (divisor == 0) {
throw new ArithmeticException("Division by zero");
}
long result = 0;
long temp = divisor;
while (temp <= dividend) {
temp <<= 1;
}
while (temp > divisor) {
temp >>= 1;
result <<= 1;
if (dividend >= temp) {
dividend -= temp;
result |= 1;
}
}
return result;
}
// 位运算实现快速模运算
public long fastModulo(long dividend, long divisor) {
if (divisor == 0) {
throw new ArithmeticException("Division by zero");
}
// 使用位运算优化模运算
if ((divisor & (divisor - 1)) == 0) {
// 如果除数是2的幂,使用位运算
return dividend & (divisor - 1);
}
// 否则使用常规方法
return dividend % divisor;
}
// 位运算实现快速判断奇偶
public boolean isEven(int number) {
return (number & 1) == 0;
}
// 位运算实现快速交换
public void swap(int[] arr, int i, int j) {
if (i != j) {
arr[i] ^= arr[j];
arr[j] ^= arr[i];
arr[i] ^= arr[j];
}
}
// 位运算实现快速计算绝对值
public int fastAbs(int number) {
int mask = number >> 31;
return (number + mask) ^ mask;
}
// 位运算实现快速计算最小值
public int fastMin(int a, int b) {
return b + ((a - b) & ((a - b) >> 31));
}
// 位运算实现快速计算最大值
public int fastMax(int a, int b) {
return a - ((a - b) & ((a - b) >> 31));
}
// 位运算实现快速计算2的幂
public boolean isPowerOfTwo(int number) {
return number > 0 && (number & (number - 1)) == 0;
}
// 位运算实现快速计算下一个2的幂
public int nextPowerOfTwo(int number) {
if (number <= 0) {
return 1;
}
number--;
number |= number >> 1;
number |= number >> 2;
number |= number >> 4;
number |= number >> 8;
number |= number >> 16;
number++;
return number;
}
// 位运算实现快速计算汉明重量
public int hammingWeight(int number) {
int count = 0;
while (number != 0) {
count++;
number &= (number - 1);
}
return count;
}
// 位运算实现快速计算汉明距离
public int hammingDistance(int x, int y) {
int xor = x ^ y;
return hammingWeight(xor);
}
// 位运算实现快速计算反转位
public int reverseBits(int number) {
int result = 0;
for (int i = 0; i < 32; i++) {
result <<= 1;
result |= (number & 1);
number >>= 1;
}
return result;
}
}
4. 紧凑存储 - 让内存"精打细算" 💰
生活比喻: 就像整理行李箱,把衣服卷起来,把鞋子塞进袜子,最大化利用空间!
@Service
public class CompactStorageService {
// 紧凑存储布尔数组
public static class CompactBooleanArray {
private final int[] data;
private final int size;
public CompactBooleanArray(int size) {
this.size = size;
this.data = new int[(size + 31) / 32]; // 每个int存储32个布尔值
}
public void set(int index, boolean value) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
int arrayIndex = index / 32;
int bitIndex = index % 32;
if (value) {
data[arrayIndex] |= (1 << bitIndex);
} else {
data[arrayIndex] &= ~(1 << bitIndex);
}
}
public boolean get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
int arrayIndex = index / 32;
int bitIndex = index % 32;
return (data[arrayIndex] & (1 << bitIndex)) != 0;
}
public int size() {
return size;
}
}
// 紧凑存储小整数数组
public static class CompactIntArray {
private final byte[] data;
private final int size;
private final int bitsPerElement;
public CompactIntArray(int size, int maxValue) {
this.size = size;
this.bitsPerElement = Integer.SIZE - Integer.numberOfLeadingZeros(maxValue);
this.data = new byte[(size * bitsPerElement + 7) / 8];
}
public void set(int index, int value) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
int bitOffset = index * bitsPerElement;
int byteOffset = bitOffset / 8;
int bitOffsetInByte = bitOffset % 8;
// 设置值
for (int i = 0; i < bitsPerElement; i++) {
if ((value & (1 << i)) != 0) {
data[byteOffset] |= (1 << bitOffsetInByte);
} else {
data[byteOffset] &= ~(1 << bitOffsetInByte);
}
bitOffsetInByte++;
if (bitOffsetInByte == 8) {
byteOffset++;
bitOffsetInByte = 0;
}
}
}
public int get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
int bitOffset = index * bitsPerElement;
int byteOffset = bitOffset / 8;
int bitOffsetInByte = bitOffset % 8;
int value = 0;
for (int i = 0; i < bitsPerElement; i++) {
if ((data[byteOffset] & (1 << bitOffsetInByte)) != 0) {
value |= (1 << i);
}
bitOffsetInByte++;
if (bitOffsetInByte == 8) {
byteOffset++;
bitOffsetInByte = 0;
}
}
return value;
}
public int size() {
return size;
}
}
// 紧凑存储字符串
public static class CompactStringArray {
private final char[] data;
private final int[] offsets;
private final int[] lengths;
public CompactStringArray(String[] strings) {
int totalLength = 0;
for (String str : strings) {
totalLength += str.length();
}
this.data = new char[totalLength];
this.offsets = new int[strings.length];
this.lengths = new int[strings.length];
int offset = 0;
for (int i = 0; i < strings.length; i++) {
offsets[i] = offset;
lengths[i] = strings[i].length();
strings[i].getChars(0, lengths[i], data, offset);
offset += lengths[i];
}
}
public String get(int index) {
if (index < 0 || index >= offsets.length) {
throw new IndexOutOfBoundsException();
}
return new String(data, offsets[index], lengths[index]);
}
public int size() {
return offsets.length;
}
}
// 紧凑存储对象数组
public static class CompactObjectArray<T> {
private final Object[] data;
private final int size;
public CompactObjectArray(int size) {
this.size = size;
this.data = new Object[size];
}
@SuppressWarnings("unchecked")
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return (T) data[index];
}
public void set(int index, T value) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
data[index] = value;
}
public int size() {
return size;
}
}
}
🎯 数据结构优化的实际应用
1. 缓存友好的数据结构 💾
@Service
public class CacheFriendlyDataStructureService {
// 缓存友好的数组结构
public static class CacheFriendlyArray<T> {
private final T[] data;
private final int size;
@SuppressWarnings("unchecked")
public CacheFriendlyArray(int size) {
this.size = size;
this.data = (T[]) new Object[size];
}
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return data[index];
}
public void set(int index, T value) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
data[index] = value;
}
// 批量操作,提高缓存命中率
public void batchSet(int startIndex, T[] values) {
System.arraycopy(values, 0, data, startIndex, values.length);
}
public void batchGet(int startIndex, T[] values) {
System.arraycopy(data, startIndex, values, 0, values.length);
}
public int size() {
return size;
}
}
// 缓存友好的矩阵结构
public static class CacheFriendlyMatrix {
private final double[] data;
private final int rows;
private final int cols;
public CacheFriendlyMatrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
this.data = new double[rows * cols];
}
public double get(int row, int col) {
return data[row * cols + col];
}
public void set(int row, int col, double value) {
data[row * cols + col] = value;
}
// 按行访问,提高缓存命中率
public double[] getRow(int row) {
double[] rowData = new double[cols];
System.arraycopy(data, row * cols, rowData, 0, cols);
return rowData;
}
public void setRow(int row, double[] rowData) {
System.arraycopy(rowData, 0, data, row * cols, cols);
}
// 矩阵乘法优化
public CacheFriendlyMatrix multiply(CacheFriendlyMatrix other) {
if (this.cols != other.rows) {
throw new IllegalArgumentException("Matrix dimensions mismatch");
}
CacheFriendlyMatrix result = new CacheFriendlyMatrix(this.rows, other.cols);
for (int i = 0; i < this.rows; i++) {
for (int k = 0; k < this.cols; k++) {
double aik = this.get(i, k);
for (int j = 0; j < other.cols; j++) {
result.data[i * other.cols + j] += aik * other.get(k, j);
}
}
}
return result;
}
}
}
2. 无锁数据结构 🔒
@Service
public class LockFreeDataStructureService {
// 无锁栈
public static class LockFreeStack<T> {
private volatile Node<T> head;
public void push(T value) {
Node<T> newNode = new Node<>(value);
Node<T> currentHead;
do {
currentHead = head;
newNode.next = currentHead;
} while (!compareAndSetHead(currentHead, newNode));
}
public T pop() {
Node<T> currentHead;
Node<T> newHead;
do {
currentHead = head;
if (currentHead == null) {
return null;
}
newHead = currentHead.next;
} while (!compareAndSetHead(currentHead, newHead));
return currentHead.value;
}
private boolean compareAndSetHead(Node<T> expected, Node<T> update) {
// 使用CAS操作
return UNSAFE.compareAndSwapObject(this, HEAD_OFFSET, expected, update);
}
private static class Node<T> {
final T value;
volatile Node<T> next;
Node(T value) {
this.value = value;
}
}
private static final sun.misc.Unsafe UNSAFE;
private static final long HEAD_OFFSET;
static {
try {
Field theUnsafe = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
UNSAFE = (sun.misc.Unsafe) theUnsafe.get(null);
HEAD_OFFSET = UNSAFE.objectFieldOffset(LockFreeStack.class.getDeclaredField("head"));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
// 无锁队列
public static class LockFreeQueue<T> {
private volatile Node<T> head;
private volatile Node<T> tail;
public LockFreeQueue() {
Node<T> dummy = new Node<>(null);
head = dummy;
tail = dummy;
}
public void enqueue(T value) {
Node<T> newNode = new Node<>(value);
Node<T> currentTail;
Node<T> currentTailNext;
while (true) {
currentTail = tail;
currentTailNext = currentTail.next;
if (currentTail == tail) {
if (currentTailNext == null) {
if (compareAndSetNext(currentTail, null, newNode)) {
break;
}
} else {
compareAndSetTail(currentTail, currentTailNext);
}
}
}
compareAndSetTail(currentTail, newNode);
}
public T dequeue() {
Node<T> currentHead;
Node<T> currentTail;
Node<T> currentHeadNext;
T value;
while (true) {
currentHead = head;
currentTail = tail;
currentHeadNext = currentHead.next;
if (currentHead == head) {
if (currentHead == currentTail) {
if (currentHeadNext == null) {
return null;
}
compareAndSetTail(currentTail, currentHeadNext);
} else {
if (currentHeadNext == null) {
continue;
}
value = currentHeadNext.value;
if (compareAndSetHead(currentHead, currentHeadNext)) {
break;
}
}
}
}
return value;
}
private boolean compareAndSetNext(Node<T> node, Node<T> expected, Node<T> update) {
return UNSAFE.compareAndSwapObject(node, NEXT_OFFSET, expected, update);
}
private boolean compareAndSetTail(Node<T> expected, Node<T> update) {
return UNSAFE.compareAndSwapObject(this, TAIL_OFFSET, expected, update);
}
private boolean compareAndSetHead(Node<T> expected, Node<T> update) {
return UNSAFE.compareAndSwapObject(this, HEAD_OFFSET, expected, update);
}
private static class Node<T> {
volatile T value;
volatile Node<T> next;
Node(T value) {
this.value = value;
}
}
private static final sun.misc.Unsafe UNSAFE;
private static final long HEAD_OFFSET;
private static final long TAIL_OFFSET;
private static final long NEXT_OFFSET;
static {
try {
Field theUnsafe = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
UNSAFE = (sun.misc.Unsafe) theUnsafe.get(null);
HEAD_OFFSET = UNSAFE.objectFieldOffset(LockFreeQueue.class.getDeclaredField("head"));
TAIL_OFFSET = UNSAFE.objectFieldOffset(LockFreeQueue.class.getDeclaredField("tail"));
NEXT_OFFSET = UNSAFE.objectFieldOffset(Node.class.getDeclaredField("next"));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
🛡️ 数据结构优化的注意事项
1. 内存对齐优化 📐
@Service
public class MemoryAlignmentService {
// 内存对齐的数据结构
public static class AlignedDataStructure {
private long field1; // 8字节对齐
private int field2; // 4字节对齐
private int field3; // 4字节对齐
private byte field4; // 1字节
private byte field5; // 1字节
private byte field6; // 1字节
private byte field7; // 1字节
// 构造函数
public AlignedDataStructure(long field1, int field2, int field3,
byte field4, byte field5, byte field6, byte field7) {
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
this.field4 = field4;
this.field5 = field5;
this.field6 = field6;
this.field7 = field7;
}
// getters and setters
public long getField1() { return field1; }
public void setField1(long field1) { this.field1 = field1; }
public int getField2() { return field2; }
public void setField2(int field2) { this.field2 = field2; }
public int getField3() { return field3; }
public void setField3(int field3) { this.field3 = field3; }
public byte getField4() { return field4; }
public void setField4(byte field4) { this.field4 = field4; }
public byte getField5() { return field5; }
public void setField5(byte field5) { this.field5 = field5; }
public byte getField6() { return field6; }
public void setField6(byte field6) { this.field6 = field6; }
public byte getField7() { return field7; }
public void setField7(byte field7) { this.field7 = field7; }
}
// 内存局部性优化
public static class LocalityOptimizedStructure {
private final int[] data;
private final int size;
public LocalityOptimizedStructure(int size) {
this.size = size;
this.data = new int[size];
}
// 顺序访问,提高缓存命中率
public int sum() {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += data[i];
}
return sum;
}
// 批量操作,减少缓存失效
public void batchUpdate(int[] updates) {
for (int i = 0; i < updates.length && i < size; i++) {
data[i] = updates[i];
}
}
}
}
2. NUMA优化 🏗️
@Service
public class NUMAOptimizationService {
// NUMA感知的数据结构
public static class NUMAwareStructure {
private final int[] data;
private final int size;
private final int numaNode;
public NUMAwareStructure(int size, int numaNode) {
this.size = size;
this.numaNode = numaNode;
this.data = new int[size];
// 绑定到特定的NUMA节点
bindToNUMANode(numaNode);
}
private void bindToNUMANode(int node) {
// 使用JNI调用系统API绑定到NUMA节点
// 这里简化实现
log.info("绑定到NUMA节点: {}", node);
}
public int get(int index) {
return data[index];
}
public void set(int index, int value) {
data[index] = value;
}
public int size() {
return size;
}
}
// NUMA感知的线程池
public static class NUMAwareThreadPool {
private final ExecutorService[] executors;
private final int numaNodes;
public NUMAwareThreadPool(int numaNodes) {
this.numaNodes = numaNodes;
this.executors = new ExecutorService[numaNodes];
for (int i = 0; i < numaNodes; i++) {
executors[i] = Executors.newFixedThreadPool(4);
}
}
public void execute(int numaNode, Runnable task) {
if (numaNode >= 0 && numaNode < numaNodes) {
executors[numaNode].execute(task);
} else {
executors[0].execute(task);
}
}
public void shutdown() {
for (ExecutorService executor : executors) {
executor.shutdown();
}
}
}
}
📊 数据结构优化监控:让性能可视化
@Component
public class DataStructureOptimizationMonitor {
private final MeterRegistry meterRegistry;
private final Timer operationTimer;
private final Counter operationCounter;
public DataStructureOptimizationMonitor(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
this.operationTimer = Timer.builder("datastructure.operation.time")
.register(meterRegistry);
this.operationCounter = Counter.builder("datastructure.operation.count")
.register(meterRegistry);
}
public void recordOperation(Duration duration, String operationType) {
operationTimer.record(duration);
operationCounter.increment(Tags.of("operation", operationType));
}
}
🎉 总结:数据结构优化让程序"建筑"更稳固
数据结构优化就像生活中的各种"建筑"技巧:
- 选择合适的数据结构 = 选择最合适的建筑材料 🏗️
- 自定义数据结构 = 量身定制建筑方案 ✂️
- 位运算优化 = 使用高效的计算工具 🚀
- 紧凑存储 = 精打细算利用空间 💰
通过合理使用数据结构优化,我们可以:
- 🚀 大幅提升程序性能
- 💰 减少内存使用
- ⚡ 改善系统响应
- 🎯 提高代码质量
记住:数据结构优化不是万能的,但它是性能提升的基础! 合理使用数据结构优化,让你的Java应用运行如建筑般稳固! ✨
"数据结构优化就像魔法,让程序建筑更稳固,让性能更卓越!" 🪄🏗️