对比在ConcurrentLinkedQueue中查询队列中元素数量size()和isEmpty()的性能差距
package com.dwz.concurrent; import java.util.concurrent.ConcurrentLinkedQueue; /** * 并发集合 * 对比在ConcurrentLinkedQueue中查询队列中元素数量size()和isEmpty()的性能差距 */ public class ConcurrentLinkedQueueExample { public static void useSize() { final ConcurrentLinkedQueue<Long> queue = new ConcurrentLinkedQueue<>(); for(int i = 0; i < 100000; i++) { queue.offer(System.nanoTime()); } System.out.println("========= offer done =========="); long startTime = System.currentTimeMillis(); while(queue.size() > 0) { queue.poll(); } System.out.println("========= poll done =========="); System.out.println("useSize: " + (System.currentTimeMillis() - startTime)); } public static void useIsEmpty() { final ConcurrentLinkedQueue<Long> queue = new ConcurrentLinkedQueue<>(); for(int i = 0; i < 100000; i++) { queue.offer(System.nanoTime()); } System.out.println("========= offer done =========="); long startTime = System.currentTimeMillis(); while(!queue.isEmpty()) { queue.poll(); } System.out.println("========= poll done =========="); System.out.println("useIsEmpty: " + (System.currentTimeMillis() - startTime)); } public static void main(String[] args) { useSize(); useIsEmpty(); } }
代码运行结果
========= offer done ========== ========= poll done ========== useSize: 12340 ========= offer done ========== ========= poll done ========== useIsEmpty: 3
测试结果:
ConcurrentLinkedQueue的isEmpty()比size()效率高很多