当前位置:网站首页>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 (4)
- Speed up the energy Internet of things. What can low-power Internet of things technology represented by Zeta do?
- EPF: a fuzzy testing framework for network protocols based on evolution, protocol awareness and coverage guidance
- (Video + graphics and text) introduction to machine learning series - Chapter 4 naive Bayes
- How to solve the "safe startup function prevents the operating system from starting" prompt when installing windows10 on parallel desktop?
- What are the application fields of digital twins in industry?
- Kubedl hostnetwork: accelerating the efficiency of distributed training communication
- 2020.2.14
- [source code] VB6 chat robot
- [complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!
猜你喜欢

It is forbidden to splice SQL in code
![[complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!](/img/3f/75b3125f8779e6cf9467a30fd7eeb4.jpg)
[complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!
![[C language] break and continue in switch statement](/img/ae/5967fefcf3262c9d3096e5c7d644fd.jpg)
[C language] break and continue in switch statement
![[MySQL] classification of multi table queries](/img/96/2e51ae8d52ea8184945e0540ce18f5.jpg)
[MySQL] classification of multi table queries

Alibaba cloud container service differentiation SLO hybrid technology practice
![[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

Idea set class header comments

Recommendation of knowledge base management system

Solve the problem that the kaggle account registration does not display the verification code

Tencent interview: can you find the number of 1 in binary?
随机推荐
[2021]NeRF in the Wild: Neural Radiance Fields for Unconstrained Photo Collections
Recommendation of knowledge base management system
Analysis: misunderstanding of choosing WMS warehouse management system
ISBN number
How to trade spot gold safely?
挖财帮个人开的证券账户安全吗?是不是有套路
Make small tip
A method to solve Bert long text matching
No qualifying bean of type ‘com. netflix. discovery. AbstractDiscoveryClientOptionalArgs<?>‘ available
Entropy and full connection layer
2022 system integration project management engineer examination knowledge points: software development model
(Video + graphics and text) introduction to machine learning series - Chapter 4 naive Bayes
ITK learning notes (VII) the position of ITK rotation direction remains unchanged
Idea integrates Microsoft TFs plug-in
D25:sequence search (sequence search, translation + problem solving)
Kubedl hostnetwork: accelerating the efficiency of distributed training communication
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
Gossip about redis source code 76
Idea a method for starting multiple instances of a service
Distributed transaction -- middleware of TCC -- selection / comparison