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


以前公司领导说的程序员应该持用工匠精神,作为一个程序员应该时刻的严格要求自己,对代码精雕细琢,所以这片博客将会对我以往的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
    
复制代码

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

转载于:https://juejin.im/post/5c484b4ce51d4526e57d98e9

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值