java programming performance optimization

Recent machine memory and full, the new machine's memory, but also should take a look at our review of the code, there are a lot of code written in too casual, these bad habits or do not understand the language of the program is to suppress the pressure should take a.

The following is a summary of some of the reference network resources and some local programming in java to do as much as possible - 
1. Try suitable occasions singleton
Singleton can reduce the burden of load, reduce the time to load and improve the efficiency of the load, but not all places are suitable for a single case, in simple terms, a single case mainly applies to the following three aspects
First, control the use of resources, synchronize concurrent access to resources controlled by a thread
Second, control generates instance, in order to save resources
Third, control data sharing, under conditions not directly related to the establishment, so that multiple unrelated communicate between processes or threads - 2. Try to avoid using static random variable 
 
You know, when an object is defined as stataic variable is referenced, gc usually does not reclaim the memory occupied by the object, such as
public class A{
static B b = new B();
}
At this static variable b life cycle synchronized with the Class A, Class A if not uninstall, then b objects of permanent memory, until the program is terminated. - 
3. Try to avoid excessive and create normal java object
Try to avoid frequent method calls, circulating new objects, due to the system not only takes time to create objects, but also to spend time on these objects for garbage collection and disposal, within the range we can control, most
Object reuse large limits, preferably use an array of basic data types or objects instead. 
-
4. Try to use the final modifier
With the final modifier class is not derived. In the Java core API, there are many examples of final applications, such as java.lang.String. Final covering prevents the user specified length () method of class String. Further, if a class is final, then all such methods are final. java compiler will look for opportunities to inline (inline) all of the final method (which the compiler and the specific implementation dependent). This can improve the performance by an average of 50%. 
-
The possible use of local variables
Delivery method call parameters and temporary variables created in the call are stored in the stack (Stack), faster. Other variables, such as static variables, instance variables, etc., are in the heap (Heap) to create, slowly. - 
6. Try to deal with two basic types of packaging type and place of use
Although the basic types and the type of packaging during use can be interchangeable, but they both memory area is generated completely different basic types of data processing are generated and processed in the stack, a package type object in the heap generating instance.
In the collection class object has an object type of process suitable for packaging need, other processes advocate the use of basic types. - 
7. caution synchronized, a method to minimize synchronize
All know, is synchronized to a lot of overhead expense, and may even cause a deadlock, so try to avoid unnecessary synchronization control. When synchronize method is called, it will direct the current object lock, other threads can not call other methods of the current object before executing the method. Method synchronize it as small as possible, and should be used instead of the sync block synchronization method. - 
8. make use StringBuilder string concatenation and StringBuffer
This is not to speak of - 
9. Try not to use finalize method
实际上,将资源清理放在finalize方法中完成是非常不好的选择,由于GC的工作量很大,尤其是回收Young代内存时,大都会引起应用程序暂停,所以再选择使用finalize方法进行资源清理,会导致GC负担更大,程序运行效率更差。 
-
10.尽量使用基本数据类型代替对象
String str = "hello";
上面这种方式会创建一个“hello”字符串,而且JVM的字符缓存池还会缓存这个字符串;
String str = new String("hello");
此时程序除创建字符串外,str所引用的String对象底层还包含一个char[]数组,这个char[]数组依次存放了h,e,l,l,o 
-
11.单线程应尽量使用HashMap, ArrayList
HashTable,Vector等使用了同步机制,降低了性能。 
-
12.尽量合理的创建HashMap
当你要创建一个比较大的hashMap时,充分利用另一个构造函数
public HashMap(int initialCapacity, float loadFactor)
避 免HashMap多次进行了hash重构,扩容是一件很耗费性能的事,在默认中initialCapacity只有16,而loadFactor是 0.75,需要多大的容量,你最好能准确的估计你所需要的最佳大小,同样的Hashtable,Vectors也是一样的道理。 
-
13.尽量减少对变量的重复计算
for(int i=0;i<list.size();i++)
应该改为
for(int i=0,len=list.size();i<len;i++)
并且在循环中应该避免使用复杂的表达式,在循环中,循环条件会被反复计算,如果不使用复杂表达式,而使循环条件值不变的话,程序将会运行的更快。  
-
14.尽量避免不必要的创建
A a = new A();
if(i==1){list.add(a);}
应该改为
if(i==1){
A a = new A();
list.add(a);} 
-
15.尽量在finally块中释放资源
程序中使用到的资源应当被释放,以避免资源泄漏。这最好在finally块中去做。不管程序执行的结果如何,finally块总是会执行的,以确保资源的正确关闭。  
-
16.尽量使用移位来代替'a/b'的操作
"/"是一个代价很高的操作,使用移位的操作将会更快和更有效
int num = a / 4;
int num = a / 8;
应该改为
int num = a >> 2;
int num = a >> 3;
但注意的是使用移位应添加注释,因为移位操作不直观,比较难理解 
-
17.尽量使用移位来代替'a*b'的操作
同样的,对于'*'操作,使用移位的操作将会更快和更有效
int num = a * 4;
int num = a * 8;
应该改为
int num = a << 2;
int num = a << 3; 
-
18.尽量确定StringBuffer的容量
StringBuffer 的构造器会创建一个默认大小(通常是16)的字符数组。在使用中,如果超出这个大小,就会重新分配内存,创建一个更大的数组,并将原先的数组复制过来,再 丢弃旧的数组。在大多数情况下,你可以在创建 StringBuffer的时候指定大小,这样就避免了在容量不够的时候自动增长,以提高性能。 
如:StringBuffer buffer = new StringBuffer(1000);   
-
19.尽量早释放无用对象的引用
大部分时,方法局部引用变量所引用的对象 会随着方法结束而变成垃圾,因此,大部分时候程序无需将局部,引用变量显式设为null。
例如:
Public void test(){
Object obj = new Object();
……
Obj=null;
}
上面这个就没必要了,随着方法test()的执行完成,程序中obj引用变量的作用域就结束了。但是如果是改成下面:
Public void test(){
Object obj = new Object();
……
Obj=null;
//执行耗时,耗内存操作;或调用耗时,耗内存的方法
……
}
这时候就有必要将obj赋值为null,可以尽早的释放对Object对象的引用。 
-
20.尽量避免使用二维数组
二维数据占用的内存空间比一维数组多得多,大概10倍以上。 
-
21.尽量避免使用split
除 非是必须的,否则应该避免使用split,split由于支持正则表达式,所以效率比较低,如果是频繁的几十,几百万的调用将会耗费大量资源,如果确实需 要频繁的调用split,可以考虑使用apache的StringUtils.split(string,char),频繁split的可以缓存结果。 
-
22.ArrayList & LinkedList
一 个是线性表,一个是链表,一句话,随机查询尽量使用ArrayList,ArrayList优于LinkedList,LinkedList还要移动指 针,添加删除的操作LinkedList优于ArrayList,ArrayList还要移动数据,不过这是理论性分析,事实未必如此,重要的是理解好2 者得数据结构,对症下药。 
-
23.尽量使用System.arraycopy ()代替通过来循环复制数组
System.arraycopy() 要比通过循环来复制数组快的多  
-
24.尽量缓存经常使用的对象
尽可能将经常使用的对象进行缓存,可以使用数组,或HashMap的容器来进行缓存,但这种方式可能导致系统占用过多的缓存,性能下降,推荐可以使用一些第三方的开源工具,如EhCache,Oscache进行缓存,他们基本都实现了FIFO/FLU等缓存算法。 
-
25.尽量避免非常大的内存分配
有时候问题不是由当时的堆状态造成的,而是因为分配失败造成的。分配的内存块都必须是连续的,而随着堆越来越满,找到较大的连续块越来越困难。 
-
26.慎用异常
当 创建一个异常时,需要收集一个栈跟踪(stack track),这个栈跟踪用于描述异常是在何处创建的。构建这些栈跟踪时需要为运行时栈做一份快照,正是这一部分开销很大。当需要创建一个 Exception 时,JVM 不得不说:先别动,我想就您现在的样子存一份快照,所以暂时停止入栈和出栈操作。栈跟踪不只包含运行时栈中的一两个元素,而是包含这个栈中的每一个元素。
如 果您创建一个 Exception ,就得付出代价。好在捕获异常开销不大,因此可以使用 try-catch 将核心内容包起来。从技术上讲,您甚至可以随意地抛出异常,而不用花费很大的代价。招致性能损失的并不是 throw 操作——尽管在没有预先创建异常的情况下就抛出异常是有点不寻常。真正要花代价的是创建异常。幸运的是,好的编程习惯已教会我们,不应该不管三七二十一就 抛出异常。异常是为异常的情况而设计的,使用时也应该牢记这一原则。 

7.慎用synchronized,尽量减小synchronize的方法
re:同意,不过文中有个地方说错了,使用synchronized关键字并不一定都是锁定当前对象的,要看具体的锁是什么。如果是在方法上加的synchronized,则是以对象本身为锁的,如果是静态方法则锁的粒度是类。
---------------
9.尽量不要使用finalize方法
re:同意,其实不推荐用finalize方法的根本原因在于,JVM的规范并不保证何时执行该方法,所以用这个方法来释放资源很不合适,有可能造成长时间资源得不到释放。
---------------
16.尽量使用移位来代替'a/b'的操作;17.尽量使用移位来代替'a*b'的操作
re:个人不太同意这两条。这样做确实有更好的性能,但是却牺牲了可读性。这两个操作符对很多程序员来说并不直观。我认为在如今硬件价格不那么昂贵的情况下,略微牺牲一些性能,换来更好的可读性和可维护性是好的选择。
19. Try to release as early as useless reference to the object when the most part, the local method reference object variables referenced with the end of the method will become garbage, therefore, most of the time without having to program locally, reference variables explicitly set to null. For example: Public void test () { Object obj = new new Object (); ...... the Obj = null; } above, this is not necessary, and with the method test () are executed, the program references the variable obj scope ends a. But if it is changed to the following: Public void Test () { Object obj = new new Object (); ...... the Obj = null; // time-consuming, consuming memory operation; call or time consuming, memory consumption method ......    
   
   
   
   
   
   
   
   
   
   
   
   
   
   
 

If the Object obj = new Object (); if this object is not a large object, this necessary? Obj = null; just tell jvm This object has been garbage, as to when recovery can not be determined! This readability is not good!

Reproduced in: https: //my.oschina.net/usenrong/blog/197875

Guess you like

Origin blog.csdn.net/weixin_34414650/article/details/92028907