当前位置:网站首页>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 .
边栏推荐
- Double efficiency. Six easy-to-use pychar plug-ins are recommended
- Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
- Idea integrates Microsoft TFs plug-in
- Bodong medical sprint Hong Kong stocks: a 9-month loss of 200million Hillhouse and Philips are shareholders
- Iclr2022: how does AI recognize "things I haven't seen"?
- Solution to the impact of Remote Code Execution Vulnerability of log4j2 component on December 9, 2021
- Report on the construction and development mode and investment mode of sponge cities in China 2022-2028
- Pytorch learning notes 5: model creation
- ISBN number
- Gossip about redis source code 79
猜你喜欢

JDBC Technology
![[2021]NeRF in the Wild: Neural Radiance Fields for Unconstrained Photo Collections](/img/c6/3dc7d01600f6713afdbb4cf3df5238.jpg)
[2021]NeRF in the Wild: Neural Radiance Fields for Unconstrained Photo Collections

Kubedl hostnetwork: accelerating the efficiency of distributed training communication

NLP Chinese corpus project: large scale Chinese natural language processing corpus

It is forbidden to splice SQL in code

Analysis on the scale of China's smart health industry and prediction report on the investment trend of the 14th five year plan 2022-2028 Edition

Vscode regular match replace console log(.*)

Joint examination of six provinces 2017

Yyds dry goods inventory three JS source code interpretation - getobjectbyproperty method

Enter MySQL in docker container by command under Linux
随机推荐
Global and Chinese market of process beer equipment 2022-2028: Research Report on technology, participants, trends, market size and share
It is forbidden to splice SQL in code
Open 2022 efficient office, starting from project management
ESP Arduino playing with peripherals (V) basic concept of interrupt and timer interrupt
Global and Chinese market of glossometer 2022-2028: Research Report on technology, participants, trends, market size and share
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?
Analysis on the scale of China's smart health industry and prediction report on the investment trend of the 14th five year plan 2022-2028 Edition
Research Report on the scale prediction of China's municipal engineering industry and the prospect of the 14th five year plan 2022-2028
Gossip about redis source code 74
Gossip about redis source code 82
Cannot build artifact 'test Web: War expanded' because it is included into a circular depend solution
Solve the problem that the kaggle account registration does not display the verification code
[source code] VB6 chat robot
D23:multiple of 3 or 5 (multiple of 3 or 5, translation + solution)
【leetcode】300. Longest increasing subsequence (dynamic programming, dichotomy)
2022 Guangdong Provincial Safety Officer a certificate third batch (main person in charge) simulated examination and Guangdong Provincial Safety Officer a certificate third batch (main person in charg
Gossip about redis source code 77
Bodong medical sprint Hong Kong stocks: a 9-month loss of 200million Hillhouse and Philips are shareholders
(Introduction to database system | Wang Shan) Chapter V database integrity: Exercises
Gossip about redis source code 76