Java code optimization summary

  Code optimization is a very important topic. Generally speaking, there are two main goals of code optimization, one is to reduce the size of the code, and the other is to improve the efficiency of the code.

  There are many details of code optimization, here are some of them:

  1. Try to specify the final modifier of classes and methods.

  A class with the final modifier is not derivable. In the Java core API, there are many examples of the application of final, such as java.lang.String, the entire class is final.

  Specifying the final modifier for a class makes the class non-inheritable, and specifying the final modifier for a method makes the method non-overridable.

  If a class is designated as final, all methods of that class are final.

  The Java compiler will look for opportunities to inline all final methods, and inlining plays an important role in improving the efficiency of Java.

  2. Reuse objects as much as possible

  Especially for the use of String objects, StringBuilder/StringBuffer should be used instead when string concatenation occurs. StringBuffer is thread-safe, but less efficient than StringBuilder, which is not thread-safe ; therefore, StringBuilder is recommended unless multithreaded .

  Since the Java virtual machine not only takes time to generate objects, but may also take time to garbage collect and process these objects in the future, 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 calling the method and the temporary variables created in the call are stored in the stack, so the speed is faster; other variables, such as static variables, instance variables, etc., are created in the heap, which is slower.

  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 performing database connection and I/O stream operations. After use, close it in time to release resources. Because the operation of these large objects will cause a lot of overhead in the system, a little carelessness will lead to serious consequences.

  5. Minimize double counting of variables

  Clarify a concept, calling a method, even if there is only one statement in the method, is consuming, including creating a stack frame, protecting the scene when calling a method, and restoring the scene when the method is called. So for example the following operation:

  6. When using the singleton mode, try to use the lazy loading strategy, that is, create it only when needed.

  7. Use exceptions with caution

  Exceptions are bad for performance. Throwing an exception first creates a new object. The constructor of the Throwable interface calls a local synchronization method named fillInStackTrace(). The fillInStackTrace() method checks the stack and collects call trace information. Whenever an exception is thrown, the Java Virtual Machine has to adjust the call stack because a new object is created during processing. Exceptions should only be used for error handling and should not be used to control program flow.

  8. Don't use try...catch... in the loop, it should be placed in the outermost layer

  Unless absolutely necessary. If you write like this for no reason, as long as your leader is more senior and obsessive-compulsive, 80% of them will scold you for writing such garbage code.

  9. If the length of the content to be added can be estimated, specify the initial length for the underlying collection and tool class implemented in the form of an array

  For example, ArrayList, LinkedLlist, StringBuilder, StringBuffer, HashMap, HashSet, etc. Take StringBuilder as an example:

  (1) StringBuilder() // 16 characters of space are allocated by default

  (2) StringBuilder(int size) // allocates a space of size characters by default

  (3) StringBuilder(String str) // 16 characters + str.length() character space is allocated by default

  The initialization capacity of the class can be set through the default allocation space of the class, which can significantly improve the performance. For example StringBuilder, length indicates the number of characters that the current StringBuilder can hold. Because when StringBuilder reaches its maximum capacity, it will increase its own capacity to 2 times the current capacity plus 2, whenever StringBuilder reaches its maximum capacity, it has to create a new character array, and then put the old one Copying the contents of a character array to a new character array is a very expensive operation. Just imagine, if it can be estimated that about 5000 characters will be stored in the character array without specifying the length, the nearest power of 2 to 5000 is 4096, and the 2 added for each expansion does not matter, then:

  (1) On the basis of 4096, apply for a character array with a size of 8194, which is equivalent to applying for a character array with a size of 12290 at a time. If you can specify a character array with a size of 5000 at the beginning, it will save more than doubled Space

  (2) Copy the original 4096 characters into a new character array. In this case, it not only wastes memory space, but also reduces the efficiency of code operation.

  Therefore, it is not wrong to set a reasonable initialization capacity for the underlying collections and tool classes implemented by arrays, which will bring immediate results. However, note that for a collection implemented as an array + linked list like HashMap, do not set the initial size to be the same as your estimated size, because the possibility of only connecting one object to a table is almost 0. The initial size is recommended to be set to the power of 2. If it can be estimated that there are 2000 elements, it can be set to new HashMap(128) or new HashMap(256).

  10. When copying large amounts of data, use the System.arraycopy() command

  11. Multiplication and division use shift operations

  Using shift operations can greatly improve performance, because at the bottom of the computer, bitwise operations are the most convenient and fastest. In addition, although the shift operation is fast, it may make the code less understandable, so it is best to add corresponding comments.

  12. Don't keep creating object references in the loop

  这种做法会导致内存中有count份Object对象引用存在,count很大的话,就耗费内存了。应该使内存中只有一份Object对象引用,每次new Object()的时候,Object对象引用指向不同的Object罢了,但是内存中只有一份,这样就大大节省了内存空间。

  13、基于效率和类型检查的考虑,应该尽可能使用array,无法确定数组大小时才使用ArrayList

  14、尽量使用HashMap、ArrayList、StringBuilder,除非线程安全需要,否则不推荐使用Hashtable、Vector、StringBuffer,后三者由于使用同步机制而导致了性能开销较大。

  15、不要将数组声明为public static final

  因为这毫无意义,这样只是定义了引用为static final,数组的内容还是可以随意改变的,将数组声明为public更是一个安全漏洞,这意味着这个数组可以被外部类所改变。

  16、尽量在合适的场合使用单例

  使用单例可以减轻加载的负担、缩短加载的时间、提高加载的效率,但并不是所有地方都适用于单例,简单来说,单例主要适用于以下三个方面:

  (1)控制资源的使用,通过线程同步来控制资源的并发访问。

  (2)控制实例的产生,以达到节约资源的目的。

  (3)控制数据的共享,在不建立直接关联的条件下,让多个不相关的进程或线程之间实现通信。  

  17、尽量避免随意使用静态变量

  要知道,当某个对象被定义为static的变量所引用,那么GC通常是不会回收这个对象所占有的堆内存的,从而无谓地加大内存开销。

  18、及时清除不再需要的会话

  为了清除不再活动的会话,许多应用服务器都有默认的会话超时时间,一般为30分钟。当应用服务器需要保存更多的会话时,如果内存不足,那么操作系统会把部分数据转移到磁盘,应用服务器也可能根据MRU(最近最频繁使用)算法把部分不活跃的会话转储到磁盘,甚至可能抛出内存不足的异常。如果会话要被转储到磁盘,那么必须要先被序列化,在大规模集群中,对对象进行序列化的代价是很昂贵的。因此,当会话不再需要时,应当及时调用HttpSession的invalidate()方法清除会话。

  19、实现RandomAccess接口的集合比如ArrayList,应当使用最普通的for循环而不是foreach循环来遍历

  这是JDK推荐给用户的。JDK API对于RandomAccess接口的解释是:实现RandomAccess接口用来表明其支持快速随机访问,此接口的主要目的是允许一般的算法更改其行为,从而将其应用到随机或连续访问列表时能提供良好的性能。实际经验表明,实现RandomAccess接口的类实例,假如是随机访问的,使用普通for循环效率将高于使用foreach循环;反过来,如果是顺序访问的,则使用Iterator会效率更高。

  foreach循环的底层实现原理就是迭代器Iterator。

  20、使用同步代码块替代同步方法

  除非能确定整个方法都是需要进行同步的,否则尽量使用同步代码块,避免对那些不需要进行同步的代码也进行了同步,从而影响代码执行效率。

  21、将常量声明为static final,并以大写命名

  这样在编译期间就可以把这些内容放入常量池中,避免运行期间计算生成常量的值。另外,将常量的名字以大写命名也可以方便地区分出常量与变量。

  22、不要创建一些不使用的对象,不要导入一些不使用的类

  这毫无意义,如果代码中出现”The value of the local variable i is not used”、”The import java.util is never used”,那么请删除这些无用的内容。

  23、程序运行过程中避免使用反射

  反射是Java提供给用户的一个很强大的功能,功能强大往往意味着效率不高。不建议在程序运行过程中使用,尤其是频繁使用反射机制,特别是Method的invoke方法,如果确实有必要,一种建议性的做法是将那些需要通过反射加载的类在项目启动的时候通过反射实例化出一个对象并放入内存,从而提高效率。毕竟用户只关心和对端交互的时候获取最快的响应速度,并不关心对端的项目启动花多久时间。

  24、使用数据库连接池和线程池

  这两个池都是用于重用对象的,前者可以避免频繁地打开和关闭连接,后者可以避免频繁地创建和销毁线程。

  25、使用带缓冲的输入输出流进行IO操作

  带缓冲的输入输出流,即BufferedReader、BufferedWriter、BufferedInputStream、BufferedOutputStream,这可以极大地提升IO效率。

  26、顺序插入和随机访问比较多的场景使用ArrayList,元素删除和中间插入比较多的场景使用LinkedList。

  27、不要让public方法中有太多的形参

  public方法是对外提供的方法,如果给这些方法太多形参的话主要有两点坏处:

  (1)违反了面向对象的编程思想,Java讲求一切都是对象,太多的形参,和面向对象的编程思想并不契合。

  (2)参数太多势必导致方法调用的出错概率增加。

  比如,我们用JDBC写一个insertStudentInfo方法,有10个学生信息字段要插如Student表中,可以把这10个参数封装在一个实体类(如Set集合)中,作为insert方法的形参。

  28、字符串变量和字符串常量equals的时候将字符串常量写在前面,这样可以避免空指针异常。

  29、尽管Java的”if (i == 1)”和”if (1 == i)”在语义上没有任何区别,但是从阅读习惯上讲,建议使用前者会更好些。

  30、不要对数组使用toString()方法,这样做要么输出数组的地址,要么有可能因为数组为空而导致空指针异常。如果要遍历数组arr的元素,可以直接使用Arrays.toString(arr)。

  31、不要对超出范围的基本数据类型做向下强制转型,这种做法往往会造成精度损失。

  32、公用的集合类中不使用的数据一定要及时remove掉

  如果一个集合类是公用的,那么这个集合里面的元素是不会自动释放的,因为始终有引用指向它们。所以,如果公用集合里面的某些数据不使用而不去remove掉它们,那么将会造成这个公用集合不断增大,使得系统有内存泄露的隐患。

  33、把一个基本数据类型转为字符串,基本数据类型.toString()是最快的方式,String.valueOf(数据)次之,数据+””最慢。

  这是由于:String.valueOf()方法底层调用了Integer.toString()方法,但是会在调用前做空判断;如Integer.toString()方法可以直接调用;i + “”,底层使用了StringBuilder实现,先用append方法拼接,再用toString()方法获取字符串。

  三者对比下来,明显是toString()最快、String.valueOf次之、数据+””最慢,

  34、使用最有效率的方式去遍历Map

  遍历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值,这样做会比较合适一些:

Set keySet = hm.keySet();

   35、对资源的close()建议分开操作  

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这块资源就不会回收了,一直占用着,这样的代码一多,是可能引起资源句柄泄露的。而改为下面的写法之后,就保证了无论如何XXX和YYY都会被close掉。

  36、慎用递归(尽量不用)

  递归会加大栈内存开销,极易引发栈内存溢出异常。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324984205&siteId=291194637