当前位置:网站首页>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 .
边栏推荐
- [leetcode] interview question 17.08 Circus tower
- A Kuan food rushed to the Shenzhen Stock Exchange: with annual sales of 1.1 billion, Hillhouse and Maotai CCB are shareholders
- Solution to the impact of Remote Code Execution Vulnerability of log4j2 component on December 9, 2021
- 1214 print diamond
- Kubedl hostnetwork: accelerating the efficiency of distributed training communication
- Gossip about redis source code 73
- China standard gas market prospect investment and development feasibility study report 2022-2028
- 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
- Gossip about redis source code 81
- D26: the nearest number (translation + solution)
猜你喜欢

How to solve the "safe startup function prevents the operating system from starting" prompt when installing windows10 on parallel desktop?

How to make icons easily

Double efficiency. Six easy-to-use pychar plug-ins are recommended

BBS forum recommendation

Tencent interview: can you pour water?
![[CSDN Q & A] experience and suggestions](/img/db/dff3173dda24ca5740729b54a81153.jpg)
[CSDN Q & A] experience and suggestions

The first game of the new year, many bug awards submitted

ESP Arduino playing with peripherals (V) basic concept of interrupt and timer interrupt

2022 t elevator repair registration examination and the latest analysis of T elevator repair

Alibaba cloud container service differentiation SLO hybrid technology practice
随机推荐
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
How will the complete NFT platform work in 2022? How about its core functions and online time?
Test the influence of influent swacth on the electromagnetic coil of quartz meter
No qualifying bean of type ‘com. netflix. discovery. AbstractDiscoveryClientOptionalArgs<?>‘ available
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
URL (data:image/png; Base64, ivborw0k... Use case
leetcode-43. String multiplication
[Mongodb] 2. Use mongodb --------- use compass
Actual combat | use composite material 3 in application
2022 free examination questions for hoisting machinery command and hoisting machinery command theory examination
D28:maximum sum (maximum sum, translation)
A method to solve Bert long text matching
Introducing Software Testing
Qtcharts notes (V) scatter diagram qscatterseries
STM32 GPIO CSDN creative punch in
2022 chemical automation control instrument examination content and chemical automation control instrument simulation examination
Global and Chinese markets for coronary artery disease treatment devices 2022-2028: Research Report on technology, participants, trends, market size and share
It is the most difficult to teach AI to play iron fist frame by frame. Now arcade game lovers have something
Shell script three swordsman sed
D25:sequence search (sequence search, translation + problem solving)