当前位置:网站首页>Optimization of for loop
Optimization of for loop
2022-07-04 00:19:00 【Hello】
Operations that often use cyclic time-consuming calculations , In especial for loop , If not handled well , It takes quite a long time , If handled and written properly, it will greatly improve efficiency , Here's a summary for Common optimization methods of loops .
One 、 Eliminate the method call when the loop terminates the judgment
Before optimization :
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
** advantage :** More common , Easy to understand
** shortcoming :** Count every time list.size()
1️⃣ Optimize one : Will calculate list Length of the code extracted
int m = list.size();
for (int i = 0; i < m; i++) {
System.out.println(list.get(i));
}
** advantage :** You don't have to calculate every time list The length of
shortcoming :
- m The scope of is not small enough , Violation of the minimum scope principle .
- Can't be in for Operation in cycle list Size , Such as removing or adding a new element
explain :
list.size() Each cycle is executed , This will undoubtedly affect the performance of the program , So it should be put out of the loop , Replace with a variable , The comparison before and after optimization is also obvious .
2️⃣ Optimization II : Will calculate list Length of the code extracted
for (int i = 0, n = list.size(); i < n; i++) {
System.out.println(list.get(i));
}
** advantage :** You don't have to calculate every time , The scope of variables follows the principle of minimum scope .
3️⃣ Optimize three : In reverse order
for (int i = list.size() - 1; i >= 0; i--) {
System.out.println(list.get(i));
}
** advantage :** You don't have to calculate every time , The scope of variables follows the principle of minimum scope .
shortcoming :
- The order of results will be reversed .
- I don't seem used to , Not easy to read .
** Applicable occasions :** Independent of the order in which the results are displayed , For example, check the data before saving .
Two 、 A nested loop Outside small inside big principle ( From the outside to the inside , Loop objects size From small to large )
Before optimization :
for (int i = 0; i < 100000; i++) {
for (int j = 0; j < 10; j++) {
}
}
After optimization :
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 100000; j++) {
}
}
** understand :** This is like the difference between copying many small files and copying several large files .
3、 ... and 、 Loop nesting extracts logic that does not need a loop
Before optimization :
int a = 10, b = 11;
for (int i = 0; i < 10; i++) {
i = i * a * b;
}
After optimization :
int c = a * b;
for (int i = 0; i < 10; i++) {
i = i * c;
}
** explain :** In the code a*b Not related to circulation , To avoid double counting , It should be put outside . After optimization, the performance will be improved by several orders of magnitude , These cannot be ignored .
Four 、 Exception handling is written outside the loop
Before optimization :
for (int i = 0; i < 10; i++) {
try {
} catch (Exception e) {
}
}
After optimization :
try {
for (int i = 0; i < 10; i++) {
}
} catch (Exception e) {
}
** explain :** Catching exceptions is resource intensive , So we can't try catch Put it inside the loop , After optimization, there are also several orders of magnitude improvements .
5、 ... and 、Iterator Traverse
for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
System.out.println(it.next());
}
** advantage :** concise
6、 ... and 、jdk1.5 neographism
for (Object o : list) {
System.out.println(o);
}
advantage : Concise combination Generic Use more succinctly .
shortcoming :jdk1.4 Down incompatibility .
边栏推荐
- Analysis: misunderstanding of choosing WMS warehouse management system
- P1629 postman delivering letter
- How to solve the "safe startup function prevents the operating system from starting" prompt when installing windows10 on parallel desktop?
- Solve the problem that the kaggle account registration does not display the verification code
- NLP pre training technology development
- [Mongodb] 2. Use mongodb --------- use compass
- [complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!
- Global and Chinese markets of distributed control system (DCS) consumption 2022-2028: Research Report on technology, participants, trends, market size and share
- 【leetcode】374. Guess the size of the number
- 网上的低佣金链接安全吗?招商证券怎么开户?
猜你喜欢

How to make icons easily
![[CSDN Q & A] experience and suggestions](/img/db/dff3173dda24ca5740729b54a81153.jpg)
[CSDN Q & A] experience and suggestions

Report on prospects and future investment recommendations of China's assisted reproductive industry, 2022-2028 Edition

Private project practice sharing populate joint query in mongoose makes the template unable to render - solve the error message: syntaxerror: unexpected token r in JSON at

2022 system integration project management engineer examination knowledge points: software development model

SPI based on firmware library

How will the complete NFT platform work in 2022? How about its core functions and online time?

Introducing Software Testing

It is forbidden to splice SQL in code
![[C language] break and continue in switch statement](/img/ae/5967fefcf3262c9d3096e5c7d644fd.jpg)
[C language] break and continue in switch statement
随机推荐
Global and Chinese market of process beer equipment 2022-2028: Research Report on technology, participants, trends, market size and share
D23:multiple of 3 or 5 (multiple of 3 or 5, translation + solution)
Smart fan system based on stm32f407
MySQL is installed as a Windows Service
CSP window
[BSP video tutorial] stm32h7 video tutorial phase 5: MDK topic, system introduction to MDK debugging, AC5, AC6 compilers, RTE development environment and the role of various configuration items (2022-
Unity elementary case notes of angry birds Siki college 1-6
Private project practice sharing populate joint query in mongoose makes the template unable to render - solve the error message: syntaxerror: unexpected token r in JSON at
Tencent interview: can you find the number of 1 in binary?
Gossip about redis source code 81
Sword finger offer day 4 (Sword finger offer 03. duplicate numbers in the array, sword finger offer 53 - I. find the number I in the sorted array, and the missing numbers in sword finger offer 53 - ii
How to make recv have a little temper?
Global and Chinese market of breast cancer imaging 2022-2028: Research Report on technology, participants, trends, market size and share
2020.2.14
Version rollback revert don't reset better reset must be forced
China standard gas market prospect investment and development feasibility study report 2022-2028
Briefly understand the operation mode of developing NFT platform
想请教一下,十大劵商如何开户?在线开户是安全么?
Make small tip
D28:maximum sum (maximum sum, translation)