Code optimization is a very important topic. Some people may think it is useless. What are the small things that can be modified? What impact will the modification or not have on the running efficiency of the code? I think about this question like this, just like a whale in the sea, is it useful for it to eat a small shrimp? It was useless, but after eating more shrimps, the whale was full. The same is true for code optimization. If the project focuses on launching without bugs as soon as possible, then you can focus on the big and let go of the small at this time, and the details of the code do not need to be refined; but if there is enough time to develop and maintain the code, you must consider every aspect at this time. There are details that can be optimized. The accumulation of small optimization points one by one will definitely improve the running efficiency of the code.
The goals of code optimization are:
1. Reduce the size of the code
2. Improve the efficiency of code operation
Classes with final modifiers cannot be derived. In the Java core API, there are many examples of final applications, such as java.lang.String, where the entire class is final. Specifying the final modifier for a class prevents the class from being inherited, and specifying the final modifier for a method prevents the method from being overridden. If a class is designated as final, all methods of the class are final. The Java compiler will look for opportunities to inline all final methods. Inlining plays a significant role in improving Java running efficiency. For details, see Java runtime optimization. This can improve performance by an average of 50%.
Especially when using String objects, StringBuilder/StringBuffer should be used instead when string connections occur. Since the Java virtual machine not only spends time generating objects, it may also need to spend time garbage collecting and processing these objects in the future. Therefore, generating too many objects will have a great impact on the performance of the program.
The parameters passed when calling the method and the temporary variables created during the call are saved in the stack faster. Other variables, such as static variables and instances Variables, etc., are all created in the heap, which is slower. In addition, the contents of variables created in the stack are gone as the method ends, and no additional garbage collection is required.
During the Java programming process, be careful when performing database connections and I/O stream operations. After use, close the stream in time to release resources. Because operating these large objects will cause a lot of system overhead, a little carelessness will lead to serious consequences.
Clear a concept. Calling a method, even if there is only one statement in the method, is costly, including when creating a stack frame and calling a method. Protect the scene, restore the scene when the method is called, etc. So for example, the following operation:
for (int i = 0; i 7fcda49a0f11e42fd7dd1cefced778bd重写了Object的toString()方法。<h3>31、不要对超出范围的基本数据类型做向下强制转型</h3><p>这绝不会得到想要的结果:</p><pre class="brush:java;toolbar:false;">public static void main(String[] args){ long l = 12345678901234L; int i = (int)l; System.out.println(i); }
我们可能期望得到其中的某几位,但是结果却是:
1942892530
解释一下。Java中long是8个字节64位的,所以12345678901234在计算机中的表示应该是:
0000 0000 0000 0000 0000 1011 0011 1010 0111 0011 1100 1110 0010 1111 1111 0010
一个int型数据是4个字节32位的,从低位取出上面这串二进制数据的前32位是:
0111 0011 1100 1110 0010 1111 1111 0010
这串二进制表示为十进制1942892530,所以就是我们上面的控制台上输出的内容。从这个例子上还能顺便得到两个结论:
1、整型默认的数据类型是int,long l = 12345678901234L,这个数字已经超出了int的范围了,所以最后有一个L,表示这是一个long型数。顺便,浮点型的默认类型是double,所以定义float的时候要写成”"float f = 3.5f”
2、接下来再写一句”int ii = l + i;”会报错,因为long + int是一个long,不能赋值给int
如果一个集合类是公用的(也就是说不是方法里面的属性),那么这个集合里面的元素是不会自动释放的,因为始终有引用指向它们。所以,如果公用集合里面的某些数据不使用而不去remove掉它们,那么将会造成这个公用集合不断增大,使得系统有内存泄露的隐患。
33、把一个基本数据类型转为字符串,基本数据类型.toString()是最快的方式、String.valueOf(数据)次之、数据+”"最慢
把一个基本数据类型转为一般有三种方式,我有一个Integer型数据i,可以使用i.toString()、String.valueOf(i)、i+”"三种方式,三种方式的效率如何,看一个测试:
public static void main(String[] args){ int loopTime = 50000; Integer i = 0; long startTime = System.currentTimeMillis(); for (int j = 0; j < loopTime; j++){ String str = String.valueOf(i); } System.out.println("String.valueOf():" + (System.currentTimeMillis() - startTime) + "ms"); startTime = System.currentTimeMillis(); for (int j = 0; j < loopTime; j++){ String str = i.toString(); } System.out.println("Integer.toString():" + (System.currentTimeMillis() - startTime) + "ms"); startTime = System.currentTimeMillis(); for (int j = 0; j < loopTime; j++){ String str = i + ""; } System.out.println("i + \"\":" + (System.currentTimeMillis() - startTime) + "ms"); }
运行结果为:
String.valueOf():11ms Integer.toString():5ms i + "":25ms
所以以后遇到把一个基本数据类型转为String的时候,优先考虑使用toString()方法。至于为什么,很简单:
1、String.valueOf()方法底层调用了Integer.toString()方法,但是会在调用前做空判断
2、Integer.toString()方法就不说了,直接调用了
3、i + “”底层使用了StringBuilder实现,先用append方法拼接,再用toString()方法获取字符串
三者对比下来,明显是2最快、1次之、3最慢
遍历Map的方式有很多,通常场景下我们需要的是遍历Map中的Key和Value,那么推荐使用的、效率最高的方式是:
public static void main(String[] args){ HashMap<String, String> hm = new HashMap<String, String>(); hm.put("111", "222"); Set<Map.Entry<String, String>> entrySet = hm.entrySet(); Iterator<Map.Entry<String, String>> iter = entrySet.iterator(); while (iter.hasNext()){ Map.Entry<String, String> entry = iter.next(); System.out.println(entry.getKey() + "\t" + entry.getValue()); } }
如果你只是想遍历一下这个Map的key值,那用”Setf7e83be87db5cd2d9a8a0b8117b38cd4 keySet = hm.keySet();”会比较合适一些
意思是,比如我有这么一段代码:
try{ XXX.close(); YYY.close(); }catch (Exception e){ ... }
建议修改为:
try{ XXX.close(); }catch (Exception e) { ... } try{ YYY.close(); }catch (Exception e) { ... }
虽然有些麻烦,却能避免资源泄露。我们想,如果没有修改过的代码,万一XXX.close()抛异常了,那么就进入了cath块中了,YYY.close()不会执行,YYY这块资源就不会回收了,一直占用
The above is the detailed content of Share 35 Java code performance optimization methods. For more information, please follow other related articles on the PHP Chinese website!