以前公司领导说的程序员应该持用工匠精神,作为一个程序员应该时刻的严格要求自己,对代码精雕细琢,所以这片博客将会对我以往的code做出总结,总结java 代码调优与程序员日常工作相关的代码应该怎样写,如有不足欢迎指正,此篇博客会不断更新
(一)基本代码调优
1.for遍历操作的调优
fori:通过下标访问
foreach:是通过容器的itrator的next() 方法迭代。
迭代器:
三方面调优:
(1)fori 可预设设置 list 的大小 list.ensureCapacity(N); 提高添加新元 素的速度
(2)遍历时设置提前设置list.size(), for(int i = 0,size = list.size(); i < size ; i ++){}防止每次检测大小,效率大大提高,对集合遍历操作特别适用
(3)遍历arrayList 最好用fori .迭代器访问LinkedList 最好 ,因为LinkedList 进行随机访问时,只会进行一次列表访问;对于foreach 需要做同步检查,所以必然比fori 慢
fori && foreach从源码的角度分析
public E get(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
if(ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
return (E) ArrayList.this.elementData[offset + index];
}
public E next() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
int i = cursor;
if (i >= limit) throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException(); cursor = i + 1;
return (E) elementData[lastRet = i];
}
复制代码
实验结果如下:
tListFori = 629 //arrayList
tListEeach = 784 // arrayList
tListFori = 134932 //linkedList
tLinkForeach = 500 //linkedList
复制代码