当前位置:网站首页>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 .
边栏推荐
- Selenium library 4.5.0 keyword explanation (III)
- Recommendation of knowledge base management system
- P1629 postman delivering letter
- Correlation analysis summary
- Idea a method for starting multiple instances of a service
- 2022 system integration project management engineer examination knowledge points: software development model
- Report on the construction and development mode and investment mode of sponge cities in China 2022-2028
- Regular expressions and text processors for shell programming
- What are the application fields of digital twins in industry?
- Stock price forecast
猜你喜欢
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
Celebrate the new year | Suihua fire rescue detachment has wonderful cultural activities during the Spring Festival
Smart fan system based on stm32f407
2022 system integration project management engineer examination knowledge points: software development model
2022 examination of safety production management personnel of hazardous chemical production units and examination skills of safety production management personnel of hazardous chemical production unit
It is the most difficult to teach AI to play iron fist frame by frame. Now arcade game lovers have something
Double efficiency. Six easy-to-use pychar plug-ins are recommended
ESP Arduino playing with peripherals (V) basic concept of interrupt and timer interrupt
Detailed explanation of the relationship between Zhongtai, wechat and DDD
Enter MySQL in docker container by command under Linux
随机推荐
It is forbidden to splice SQL in code
How to solve the "safe startup function prevents the operating system from starting" prompt when installing windows10 on parallel desktop?
[NLP] text classification still stays at Bert? Duality is too strong than learning framework
Iclr2022: how does AI recognize "things I haven't seen"?
I would like to ask how the top ten securities firms open accounts? Is it safe to open an account online?
Alibaba cloud container service differentiation SLO hybrid technology practice
Kubedl hostnetwork: accelerating the efficiency of distributed training communication
Report on prospects and future investment recommendations of China's assisted reproductive industry, 2022-2028 Edition
Generic tips
网上的低佣金链接安全吗?招商证券怎么开户?
[MySQL] classification of multi table queries
ESP Arduino playing with peripherals (V) basic concept of interrupt and timer interrupt
Comment obtenir une commission préférentielle pour l'ouverture d'un compte en bourse? Est - ce que l'ouverture d'un compte en ligne est sécurisée?
Regular expressions and text processors for shell programming
Analysis of refrigeration and air conditioning equipment operation in 2022 and examination question bank of refrigeration and air conditioning equipment operation
BBS forum recommendation
ISBN number
1214 print diamond
Cannot build artifact 'test Web: War expanded' because it is included into a circular depend solution
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?