In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "what are the methods of Java code optimization". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
The goal of optimizing the code is to reduce the size of the code and improve the efficiency of the code to run. Code optimization details.
1. Specify final modifiers for classes and methods as much as possible.
Classes with final modifiers are not derivable. In the core API of Java, there are many examples of using final, such as java.lang.String, where the whole class is final. Assigning a final modifier to a class makes the class uninheritable, and assigning a final modifier to a method makes it impossible for a method to be overridden. If you specify a class as final, all the methods of that class are final. The Java compiler will look for opportunities to inline all final methods, which play an important role in improving the efficiency of Java. For more information, see Java runtime optimization. This can improve performance by an average of 50%.
2. Reuse objects as much as possible
In particular, when using String objects, you should use StringBuilder/StringBuffer instead of string concatenation. Because the Java virtual machine not only takes time to generate objects, it may also take time to garbage collect and process these objects in the future, so generating too many objects will have a great impact on the performance of the program.
3. Use local variables whenever possible
The parameters passed when the method is called and the temporary variables created in the call are saved in the stack faster, while other variables, such as static variables, instance variables, and so on, are created in the heap and are slow. In addition, the variables created in the stack are gone as the method ends, and no additional garbage collection is required.
4. Close the stream in time
In the process of Java programming, you must be careful when you connect to the database and operate the I _ big O stream, and close it in time to release resources after using it. Because the operation of these large objects will cause great overhead of the system, a little carelessness will lead to serious consequences.
5. Minimize the double calculation of variables
Make clear a concept, the call to the method, even if there is only one sentence in the method, there is consumption, including creating stack frames, protecting the scene when the method is called, restoring the site when the method is called, and so on. So for example, do the following:
For (int I = 0 position I)
< list.size();i++){......} 建议替换为: for(int i = 0;int length = list.size();i < length;i++){......} 这样,在list.size很大的时候,就减少了很多的消耗。 6、尽量采用懒加载的策略,即在需要的时候才创建* 例如: String str = "aaa"; if (i == 1){ list.add(str); } 建议替换为: if(i == 1){ String str = "aaa"; list.add(str);} 7、慎用异常 异常对性能不利。抛出异常首先要创建一个新的对象,Throwable接口的构造函数调用名为fillInStackTrace的本地同步方法,fillInStackTrace方法检查堆栈,收集调用跟踪信息。只要有异常被抛出,Java虚拟机就必须调整调用堆栈,因为在处理过程中创建了一个新的对象。异常只能用于错误处理,不应该用来控制程序流程。 8、不要在循环中使用try…catch…,应该把其放在最外层 除非不得已。如果毫无理由地这么写了,只要你的领导资深一点、有强迫症一点,八成就要骂你为什么写出这种垃圾代码来了。 9、如果能估计到待添加的内容长度,为底层以数组方式实现的集合、工具类指定初始长度 比如ArrayList、LinkedLlist、StringBuilder、StringBuffer、HashMap、HashSet等等,以StringBuilder为例: (1)StringBuilder // 默认分配16个字符的空间 (2)StringBuilder(int size) // 默认分配size个字符的空间 (3)StringBuilder(String str) // 默认分配16个字符+str.length个字符空间 可以通过类(这里指的不仅仅是上面的StringBuilder)的来设定它的初始化容量,这样可以明显地提升性能。比如StringBuilder吧,length表示当前的StringBuilder能保持的字符数量。因为当StringBuilder达到最大容量的时候,它会将自身容量增加到当前的2倍再加2,无论何时只要StringBuilder达到它的最大容量,它就不得不创建一个新的字符数组然后将旧的字符数组内容拷贝到新字符数组中--这是十分耗费性能的一个操作。试想,如果能预估到字符数组中大概要存放5000个字符而不指定长度,最接近5000的2次幂是4096,每次扩容加的2不管,那么: (1)在4096 的基础上,再申请8194个大小的字符数组,加起来相当于一次申请了12290个大小的字符数组,如果一开始能指定5000个大小的字符数组,就节省了一倍以上的空间; (2)把原来的4096个字符拷贝到新的的字符数组中去。 这样,既浪费内存空间又降低代码运行效率。所以,给底层以数组实现的集合、工具类设置一个合理的初始化容量是错不了的,这会带来立竿见影的效果。但是,注意,像HashMap这种是以数组+链表实现的集合,别把初始大小和你估计的大小设置得一样,因为一个table上只连接一个对象的可能性几乎为0。初始大小建议设置为2的N次幂,如果能估计到有2000个元素,设置成new HashMap(128)、new HashMap(256)都可以。 10、当复制大量数据时,使用System.arraycopy命令 11、乘法和除法使用移位操作 例如: for (val = 0;val < 100000;val += 5){ a = val * 8; b = val / 2;} 用移位操作可以极大地提高性能,因为在计算机底层,对位的操作是最方便、最快的,因此建议修改为: for (val = 0; val < 100000; val += 5){ a = val >1;}
The shift operation is fast, but it may make the code difficult to understand, so it's best to comment accordingly.
12. Don't keep creating object references within the loop
For example:
For (int I = 1; I < count; iTunes +) {Object obj = new Object ();}
This practice will result in the existence of count Object object references in memory. If the count is very large, memory will be consumed. It is recommended to change to:
Objecrt obj = null;for (int I = 0bot I iterator = list.iterable (); while (iterator.hasNext ()) {iterator.next ()}}
The underlying implementation principle of the foreach loop is the iterator Iterator, see Java syntax sugar 1: variable length parameters and foreach loop principle. So the second half of the sentence, "conversely, it is more efficient to use Iterator if it is accessed sequentially" means that those class instances accessed sequentially use foreach loops to traverse.
Use synchronization code blocks instead of synchronization methods
This has been made clear in the article "synchronized Lock method Block" in the multithreaded module. Unless you can determine that a whole method needs to be synchronized, try to use synchronization code blocks to avoid synchronizing those codes that do not need synchronization, thus affecting the efficiency of code execution.
21. Declare the constant as static final and name it in uppercase
This allows you to put this into the constant pool during compilation to avoid calculating the value of the generated constant at run time. In addition, it is easy to distinguish between constants and variables by naming the names of constants in uppercase.
22. Do not create objects that are not used or import classes that are not used.
This is pointless. If "The value of the local variable i is not used" or "The import java.util is never used" appear in the code, please delete the useless content.
23. Avoid using reflection when the program is running
For, see reflection. Reflection is a powerful function that Java provides to users, and powerful function often means inefficient. It is not recommended to use reflection mechanisms, especially Method's invoke method, frequently during program running. If necessary, it is recommended that classes that need to be loaded through reflection instantiate an object through reflection and put it into memory when the project starts-users only care about getting the fastest response when interacting with the peer, not about how long it takes for the peer to start the project.
Use database connection pooling and thread pooling
Both pools are used to reuse objects, the former avoiding frequent opening and closing of connections, and the latter avoiding frequent thread creation and destruction.
25. Use buffered input and output streams for IO operations
Buffered input and output streams, namely BufferedReader, BufferedWriter, BufferedInputStream, BufferedOutputStream, can greatly improve IO efficiency.
26. ArrayList is used in scenes with more sequential insertion and random access, and LinkedList is used in scenes with more element deletion and intermediate insertion. Just understand the principles of ArrayList and LinkedList.
27. Don't let too many parameters in the public method
Public methods are externally provided methods. If you give too many formal parameters to these methods, there are two main disadvantages:
1, violates the idea of object-oriented programming, Java emphasizes that everything is an object, too many parameters are not consistent with the idea of object-oriented programming. 2. Too many parameters will inevitably lead to an increase in the error probability of method calls. For example, if we write an insertStudentInfo method with JDBC, there are 10 student information fields to be inserted into the Student table. These 10 parameters can be encapsulated in an entity class as formal parameters of the insert method.
String constants are written first when string variables and string constants equals
This is a common trick if you have the following code:
String str = "123"; if (str.equals (" 123")) {.}
It is recommended to modify it as follows:
String str = "123"; if ("123" .equals (str)) {.}
The main reason for this is to avoid null pointer exceptions.
29. Please know that there is no difference between if (I = = 1) and if (1 = = I) in java, but in terms of reading habits, the former is recommended.
People usually ask if there is any difference between "if (I = 1)" and "if (1 minute = I)".
In "if (I = = 1)", the judgment condition holds, which is based on 0 and non-0, where 0 represents false and non-0 represents true, if there is such a code:
Int I = 2 * if (I = = 1) {.} else {.}
It is judged that "iTunes 1" is not valid, so it is denoted by 0, that is, false. But if:
Int I = 2 * if (I = = 1) {.} else {.}
In case a programmer is not careful, write "if (I = 1)" as "if (I = 1)", then there will be a problem. If you judge that the content in if is not 0, you will return true if you assign I to 1, but the false should be returned when I is 2 and the comparison value is 1. This situation is likely to occur in the development of if Cure + and will lead to some incomprehensible errors. Therefore, in order to avoid incorrect assignment operations in the if statement, it is recommended to write the if statement as follows:
Int I = 2 * if (I = = 1) {.} else {.}
In this way, even if the developer accidentally writes "1 = I", the CpicCraft + compiler can check it out the first time, because we can assign I to a variable as 1, but not to a constant. However, in Java, the "if (I = 1)" syntax of CAccord Cure + is impossible, because once the syntax is written, Java compiles the error "Type mismatch: cannot convert from int to boolean". However, although there is no semantic difference between "if (I = = 1)" and "if (1 = = I)" in Java, it is better to recommend the former in terms of reading habits.
30. Do not use the toString method on arrays
Take a look at what is printed using toString on the array:
Public static void main (String [] args) {int [] is = new int [] {1pm 2je 3}; System.out.println (is.toString ());}
The result is:
[I@18a992f
It is intended to print out the contents of the array, but it is possible to cause a null pointer exception because the array reference is is empty. However, although it makes no sense to the array toString, it is possible to print out the contents of the collection for the collection toString, because the collection's parent class, AbstractCollections, overrides the toString method of Object.
31. Do not make a downward forced transformation of basic data types that are out of range.
This will never get the desired result:
Public static void main (String [] args) {long l = 12345678901234L; int I = (int) 1; System.out.println (I);}
We may expect some of them, but the result is: 1942892530 explain. Long in Java is 8 bytes and 64 bits, so 12345678901234 should be represented in the computer as follows: 0000 0000 0000 101111110011 1010011110011 1100111011110010 an int data is 4 bytes 32 bits, the first 32 bits of the above binary data from the low bit is: 011110011100111000101111110010 this binary string is represented as decimal 1942892530, so it is the output on our console above. By the way, two conclusions can be drawn from this example:
1. The default data type of integer is int,long l = 12345678901234L, which is beyond the range of int, so there is an L at last, indicating that this is a long number. By the way, the default type of floating point is double, so when defining float, write "" float f = 3.5f "2, followed by" int ii = l + I; "will report an error, because long + int is a long and cannot be assigned to int.
32. Data not used in public collection classes must be remove in time.
If a collection class is common (that is, it is not a property in a method), the elements in the collection are not automatically released because there are always references to them. Therefore, if some data in the common set is not used and remove them out, it will cause the common set to grow and make the system have the hidden danger of memory leakage.
33. Convert a basic data type to a string, the basic data type. ToString is the fastest way, String.valueOf is the second, and data + "" is the slowest.
There are three ways to change a basic data type to general. I have an Integer data I. You can use i.toString, String.valueOf (I), and I + ". How efficient the three methods are? see a test:
Public static void main (String [] args) {int loopTime = 50000; Integer I = 0; long startTime = System.currentTimeMillis (); for (int j = 0; j < loopTime; jacks +) {String str = String.valueOf (I);} System.out.println ("String.valueof ():" + (System.currentTimeMillis ()-startTime) + "ms"); startTime = System.currentTimeMillis () For (int j = 0 ms j < loopTime;j++) {String str = i.toString ();} System.out.println ("Integer.valueof ():" + (System.currentTimeMillis ()-startTime) + "ms"); startTime = System.currentTimeMillis (); for (int j = 0 x j < loopTime;j++) {String str = I + "" } System.out.println ("I +\"\ ":" + (System.currentTimeMillis ()-startTime) + "ms");}
The running result is:
String.valueOf (): 11ms Integer.toString (): 5ms I + "": 25ms
So in the future, when you convert a basic data type to String, the toString method is preferred. As for why, it's simple:
1. The Integer.toString method is called at the bottom of the String.valueOf method, but it will be short before the call. 2. The Integer.toString method is not mentioned. 3, I + "" is directly called. The bottom layer uses the StringBuilder implementation, first splicing with the append method, and then using the toString method to obtain the string. By comparison, it is obvious that 2 is the fastest, the first is the second, and the third is the slowest.
34. Use the most efficient way to traverse the Map
There are many ways to traverse Map. Usually, what we need to do is to traverse Key and Value in Map. The most efficient way is recommended:
Public static void main (String [] args) {HashMap hm = new HashMap (); hm.put ("111,222"); Set entrySet = hm.entrySet (); Iterator iter = entrySet.iterator (); while (iter.hasNext ()) {Map.Entry entry = iter.next (); System.out.println (entry.getKey () +" / t "+ entry.getValue ());}}
If you just want to traverse the key value of this Map, "Set keySet = hm.keySet;" would be more appropriate.
35. Close for resources is recommended to operate separately.
It means, for example, I have this code:
Try {XXX.close (); YYY.close ();} catch (Exception e) {.}
It is recommended to modify it as follows:
Try {XXX.close ();} catch (Exception e) {.} try {YYY.close ();} catch (Exception e) {.} what are the methods of Java code optimization? thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.