Java如何编写更加快速的循环

chongq 分享于 2天前 2005阅 0人收藏此代码, 我要收藏

下面列出了几种循环方式,从效率最高到效率最低

/*
 * How To Write Faster Loops (after Dan Bornstein, Google Engineer)
 * 
 * - http://www.youtube.com/watch?v=ptjedOZEXPM
 *
 */

/* 1 (fastest) */
for (int i = initializer; i >= 0; i--) { ... }
 
/* 2 */
int limit = calculateLoopLimit();
for (int i = 0; i < limit; i++) { ... }

/* 3 */
Type[] array = getMyArray();
for (Type obj : array) { ... }

/* 4 */
for (int i = 0; i < array.length; i++) { ... }

/* 5 */
for (int i = 0; i < this.var; i++) { ... }

/* 6 */
for (int i = 0; i < obj.size(); i++) { ... }

/* 7 (slowest) */
Iterable<Type> list = getMyList();
for (Type obj : list) { ... }
//该代码片段来自于: http://www.sharejs.com/codes/java/8915

标签:
  • 循环
  • 快速
  • Java