java 中常见代码调优和业务逻辑调优


之前公司领导说的程序员应该持用工匠精神,做为一个程序员应该时刻的严格要求本身,对代码精雕细琢,因此这片博客将会对我以往的code作出总结,总结java 代码调优与程序员平常工做相关的代码应该怎样写,若有不足欢迎指正,此篇博客会不断更新java


(一)基本代码调优

1.for遍历操做的调优git

fori:经过下标访问程序员

foreach:是经过容器的itrator的next() 方法迭代。github

迭代器:bash

三方面调优:ui

(1)fori 可预设设置 list 的大小 list.ensureCapacity(N); 提升添加新元 素的速度this

(2)遍历时设置提早设置list.size(), for(int i = 0,size = list.size(); i < size ; i ++){}防止每次检测大小,效率大大提升,对集合遍历操做特别适用spa

(3)遍历arrayList 最好用fori .迭代器访问LinkedList 最好 ,由于LinkedList 进行随机访问时,只会进行一次列表访问;对于foreach 须要作同步检查,因此必然比fori 慢code

fori && foreach从源码的角度分析ci

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
    
复制代码

(二)如何优雅的书写你的业务代码

相关文章
相关标签/搜索