Home  >  Article  >  Java  >  Detailed explanation of code in Java and optimization to improve execution efficiency

Detailed explanation of code in Java and optimization to improve execution efficiency

黄舟
黄舟Original
2017-07-27 10:49:00971browse

The resources available to the program (memory, CPU time, network bandwidth, etc.) are limited. The purpose of optimization is to allow the program to complete the scheduled tasks with as few resources as possible. Optimization usually includes two aspects: reducing the size of the code and improving the operating efficiency of the code. This article mainly discusses how to improve the efficiency of code.

In Java programs, most of the causes of performance problems do not lie in the Java language, but in the program itself. It is very important to develop good coding habits, such as using the java.lang.String class and the java.util.Vector class correctly and skillfully, which can significantly improve the performance of the program. Let's analyze this issue in detail below.

1. Try to specify the final modifier of the class. Classes with final modifiers cannot be derived. In the Java core API, there are many examples of applying final, such as java.lang.String. Specifying final for the String class prevents people from overriding the length() method. In addition, if a class is designated as final, all methods of the class will be final. The Java compiler will look for opportunities to inline all final methods (this depends on the specific compiler implementation). This can improve performance by an average of 50%.

2. Try to reuse objects. Especially when using String objects, StringBuffer should be used instead when string concatenation occurs. Because the system not only takes time to generate objects, it may also take time to garbage collect and process these objects later. Therefore, generating too many objects will have a great impact on the performance of the program.

3. Try to use local variables as much as possible. The parameters passed when calling the method and the temporary variables created during the call are all saved in the stack (Stack), which is faster. Other variables, such as static variables, instance variables, etc., are created in the Heap and are slower. In addition, depending on the specific compiler/JVM, local variables may be further optimized. See Use Stack Variables Wherever Possible.

4. Do not initialize variables repeatedly. By default, when calling the constructor of a class, Java will initialize variables to certain values: all objects are set to null, integer variables (byte, short, int, long) is set to 0, float and double variables are set to 0.0, and logical values ​​are set to false. This should be especially noted when a class is derived from another class, because when an object is created using the new keyword, all constructors in the constructor chain will be automatically called.

5. In the development of JAVA + Oracle application systems, the SQL statements embedded in Java should be in uppercase as much as possible to reduce the parsing burden of the Oracle parser.

6. During Java programming, be careful when performing database connections and I/O stream operations. After use, even close to release resources. Because the operation of these large objects will cause a lot of system overhead, and a little carelessness will lead to serious consequences.

7. Because the JVM has its own GC mechanism, it does not require too much consideration by program developers, which reduces the burden on developers to a certain extent, but at the same time it also misses hidden dangers. Excessive object creation will cause It consumes a large amount of system memory and may lead to memory leaks in serious cases. Therefore, it is of great significance to ensure the timely recycling of expired objects. The condition for JVM to collect garbage is that the object is no longer referenced; however, the JVM's GC is not very smart, and even if the object meets the conditions for garbage collection, it may not be recycled immediately. Therefore, it is recommended that we manually set it to null after using the object.

8. When using synchronization mechanism, try to use method synchronization instead of code block synchronization.

9. Try to reduce the repeated calculation of variables.

For example:

for(int i = 0;i < list.size; i ++) {
             …
}

should be replaced by:

for(int i = 0,int len = list.size();i < len; i ++) {
             …
}

10. Try to use lazy loading strategy. That is, only start creating when needed.

For example:

String str = “aaa”;
             if(i == 1) {
                 list.add(str);
}

should be replaced by:

   if(i == 1) {
String str = “aaa”;
                 list.add(str);
}

11. Use exceptions with caution

Exceptions are detrimental to performance. Throwing an exception first creates a new object. The constructor of the Throwable interface calls the Native method named fillInStackTrace(). The fillInStackTrace() method checks the stack and collects call tracing information. Whenever an exception is thrown, the VM 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.

12. Do not use it in a loop:

Try {
} catch() {
}

should be placed in the outermost layer.

13. Use of StringBuffer:

StringBuffer represents a variable, writable string.

There are three construction methods:

StringBuffer ();             //默认分配16个字符的空间
StringBuffer (int size);   //分配size个字符的空间
StringBuffer (String str);   //分配16个字符+str.length()个字符空间

You can set its initial capacity through the StringBuffer constructor, which can significantly improve performance. The constructor mentioned here is StringBuffer(int length), and the length parameter indicates the number of characters that the current StringBuffer can hold. You can also use the ensureCapacity(int minimumcapacity) method to set the capacity of the StringBuffer object after it is created. First let's look at the default behavior of StringBuffer, and then find a better way to improve performance.

StringBuffer在内部维护一个字符数组,当你使用缺省的构造函数来创建StringBuffer对象的时候,因为没有设置初始化字符长度,StringBuffer的容量被初始化为16个字符,也就是说缺省容量就是16个字符。当StringBuffer达到最大容量的时候,它会将自身容量增加到当前的2倍再加2,也就是(2*旧值+2)。如果你使用缺省值,初始化之后接着往里面追加字符,在你追加到第16个字符的时候它会将容量增加到34(2*16+2),当追加到34个字符的时候就会将容量增加到70(2*34+2)。无论何事只要StringBuffer到达它的最大容量它就不得不创建一个新的字符数组然后重新将旧字符和新字符都拷贝一遍――这也太昂贵了点。所以总是给StringBuffer设置一个合理的初始化容量值是错不了的,这样会带来立竿见影的性能增益。

StringBuffer初始化过程的调整的作用由此可见一斑。所以,使用一个合适的容量值来初始化StringBuffer永远都是一个最佳的建议。

14、合理的使用Java类 java.util.Vector。

简单地说,一个Vector就是一个java.lang.Object实例的数组。Vector与数组相似,它的元素可以通过整数形式的索引访问。但是,Vector类型的对象在创建之后,对象的大小能够根据元素的增加或者删除而扩展、缩小。请考虑下面这个向Vector加入元素的例子:

Object obj = new Object();
Vector v = new Vector(100000);
for(int I=0;
I<100000; I++) { v.add(0,obj); }

  除非有绝对充足的理由要求每次都把新元素插入到Vector的前面,否则上面的代码对性能不利。在默认构造函数中,Vector的初始存储能力是10个元素,如果新元素加入时存储能力不足,则以后存储能力每次加倍。Vector类就象StringBuffer类一样,每次扩展存储能力时,所有现有的元素都要复制到新的存储空间之中。下面的代码片段要比前面的例子快几个数量级:

Object obj = new Object();
Vector v = new Vector(100000);
for(int I=0; I<100000; I++) { v.add(obj); }

  同样的规则也适用于Vector类的remove()方法。由于Vector中各个元素之间不能含有“空隙”,删除除最后一个元素之外的任意其他元素都导致被删除元素之后的元素向前移动。也就是说,从Vector删除最后一个元素要比删除第一个元素“开销”低好几倍。

  假设要从前面的Vector删除所有元素,我们可以使用这种代码:

for(int I=0; I<100000; I++)
{
 v.remove(0);
}

  但是,与下面的代码相比,前面的代码要慢几个数量级:

for(int I=0; I<100000; I++)
{
 v.remove(v.size()-1);
}

  从Vector类型的对象v删除所有元素的最好方法是:

v.removeAllElements();

  假设Vector类型的对象v包含字符串“Hello”。考虑下面的代码,它要从这个Vector中删除“Hello”字符串:

String s = "Hello";
int i = v.indexOf(s);
if(I != -1) v.remove(s);

  这些代码看起来没什么错误,但它同样对性能不利。在这段代码中,indexOf()方法对v进行顺序搜索寻找字符串“Hello”,remove(s)方法也要进行同样的顺序搜索。改进之后的版本是:

String s = "Hello";
int i = v.indexOf(s);
if(I != -1) v.remove(i);

  这个版本中我们直接在remove()方法中给出待删除元素的精确索引位置,从而避免了第二次搜索。一个更好的版本是:

String s = "Hello"; v.remove(s);

  最后,我们再来看一个有关Vector类的代码片段:

for(int I=0; I++;I < v.length)

  如果v包含100,000个元素,这个代码片段将调用v.size()方法100,000次。虽然size方法是一个简单的方法,但它仍旧需要一次方法调用的开销,至少JVM需要为它配置以及清除堆栈环境。在这里,for循环内部的代码不会以任何方式修改Vector类型对象v的大小,因此上面的代码最好改写成下面这种形式:

int size = v.size(); for(int I=0; I++;I<size)

  虽然这是一个简单的改动,但它仍旧赢得了性能。毕竟,每一个CPU周期都是宝贵的。

15、当复制大量数据时,使用System.arraycopy()命令。

16、代码重构:增强代码的可读性。

     例如:

public class ShopCart {
         private List carts ;
         …
         public void add (Object item) {
             if(carts == null) {
                 carts = new ArrayList();
}
crts.add(item);
}
public void remove(Object item) {
     if(carts. contains(item)) {
         carts.remove(item);
}
}
public List getCarts() {
     //返回只读列表
     return Collections.unmodifiableList(carts);
}
//不推荐这种方式
//this.getCarts().add(item);
     }

17、不用new关键词创建类的实例

用new关键词创建类的实例时,构造函数链中的所有构造函数都会被自动调用。但如果一个对象实现了Cloneable接口,我们可以调用它的clone()方法。clone()方法不会调用任何类构造函数。

在使用设计模式(Design Pattern)的场合,如果用Factory模式创建对象,则改用clone()方法创建新的对象实例非常简单。例如,下面是Factory模式的一个典型实现:

public static Credit getNewCredit() {
     return new Credit();
}

改进后的代码使用clone()方法,如下所示:

private static Credit BaseCredit = new Credit();
public static Credit getNewCredit() {
     return (Credit) BaseCredit.clone();
}

上面的思路对于数组处理同样很有用。

18、乘法和除法

考虑下面的代码:

for (val = 0; val < 100000; val +=5) {
alterX = val * 8; myResult = val * 2;
}

用移位操作替代乘法操作可以极大地提高性能。下面是修改后的代码:

for (val = 0; val < 100000; val += 5) {
alterX = val << 3; myResult = val << 1;
}

修改后的代码不再做乘以8的操作,而是改用等价的左移3位操作,每左移1位相当于乘以2。相应地,右移1位操作相当于除以2。值得一提的是,虽然移位操作速度快,但可能使代码比较难于理解,所以最好加上一些注释。

19、在JSP页面中关闭无用的会话。

     一个常见的误解是以为session在有客户端访问时就被创建,然而事实是直到某server端程序调用HttpServletRequest.getSession(true)这样的语句时才被创建,注意如果JSP没有显示的使用 dfa91ee3dc7e70be31b6621145c9e8db 关闭session,则JSP文件在编译成Servlet时将会自动加上这样一条语句HttpSession session = HttpServletRequest.getSession(true);这也是JSP中隐含的session对象的来历。由于session会消耗内存资源,因此,如果不打算使用session,应该在所有的JSP中关闭它。

对于那些无需跟踪会话状态的页面,关闭自动创建的会话可以节省一些资源。使用如下page指令:0a3b7182a31ab96bc63fe317bf2e190f

20、JDBC与I/O

如果应用程序需要访问一个规模很大的数据集,则应当考虑使用块提取方式。默认情况下,JDBC每次提取32行数据。举例来说,假设我们要遍历一个5000行的记录集,JDBC必须调用数据库157次才能提取到全部数据。如果把块大小改成512,则调用数据库的次数将减少到10次。

[p][/p]21、Servlet与内存使用

许多开发者随意地把大量信息保存到用户会话之中。一些时候,保存在会话中的对象没有及时地被垃圾回收机制回收。从性能上看,典型的症状是用户感到系统周期性地变慢,却又不能把原因归于任何一个具体的组件。如果监视JVM的堆空间,它的表现是内存占用不正常地大起大落。

解决这类内存问题主要有二种办法。第一种办法是,在所有作用范围为会话的Bean中实现HttpSessionBindingListener接口。这样,只要实现valueUnbound()方法,就可以显式地释放Bean使用的资源。另外一种办法就是尽快地把会话作废。大多数应用服务器都有设置会话作废间隔时间的选项。另外,也可以用编程的方式调用会话的setMaxInactiveInterval()方法,该方法用来设定在作废会话之前,Servlet容器允许的客户请求的最大间隔时间,以秒计。

22、使用缓冲标记

一些应用服务器加入了面向JSP的缓冲标记功能。例如,BEA的WebLogic Server从6.0版本开始支持这个功能,Open Symphony工程也同样支持这个功能。JSP缓冲标记既能够缓冲页面片断,也能够缓冲整个页面。当JSP页面执行时,如果目标片断已经在缓冲之中,则生成该片断的代码就不用再执行。页面级缓冲捕获对指定URL的请求,并缓冲整个结果页面。对于购物篮、目录以及门户网站的主页来说,这个功能极其有用。对于这类应用,页面级缓冲能够保存页面执行的结果,供后继请求使用。

23、选择合适的引用机制

在典型的JSP应用系统中,页头、页脚部分往往被抽取出来,然后根据需要引入页头、页脚。当前,在JSP页面中引入外部资源的方法主要有两种:include指令,以及include动作。

include指令:例如a63acf318e7c4fe9d717a9fe10196222。该指令在编译时引入指定的资源。在编译之前,带有include指令的页面和指定的资源被合并成一个文件。被引用的外部资源在编译时就确定,比运行时才确定资源更高效。

include动作:例如bf91f76f86770bb1caad1176c08485a8。该动作引入指定页面执行后生成的结果。由于它在运行时完成,因此对输出结果的控制更加灵活。但时,只有当被引用的内容频繁地改变时,或者在对主页面的请求没有出现之前,被引用的页面无法确定时,使用include动作才合算。

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

为了清除不再活动的会话,许多应用服务器都有默认的会话超时时间,一般为30分钟。当应用服务器需要保存更多会话时,如果内存容量不足,操作系统会把部分内存数据转移到磁盘,应用服务器也可能根据“最近最频繁使用”(Most Recently Used)算法把部分不活跃的会话转储到磁盘,甚至可能抛出“内存不足”异常。在大规模系统中,串行化会话的代价是很昂贵的。当会话不再需要时,应当及时调用HttpSession.invalidate()方法清除会话。HttpSession.invalidate()方法通常可以在应用的退出页面调用。

25、不要将数组声明为:public static final 。

26、HashMap的遍历效率讨论

经常遇到对HashMap中的key和value值对的遍历操作,有如下两种方法:

Map<String, String[]> paraMap = new HashMap<String, String[]>();
................//第一个循环
Set<String> appFieldDefIds = paraMap.keySet();
for (String appFieldDefId : appFieldDefIds) {
String[] values = paraMap.get(appFieldDefId);
......
}
//第二个循环
for(Entry<String, String[]> entry : paraMap.entrySet()){
String appFieldDefId = entry.getKey();
String[] values = entry.getValue();
.......
}

第一种实现明显的效率不如第二种实现。

分析如下 Setf7e83be87db5cd2d9a8a0b8117b38cd4 appFieldDefIds = paraMap.keySet(); 是先从HashMap中取得keySet

代码如下:

public Set<K> keySet() {
Set<K> ks = keySet;
return (ks != null ? ks : (keySet = new KeySet()));
}
private class KeySet extends AbstractSet<K> {
public Iterator<K> iterator() {
return newKeyIterator();
}
public int size() {
return size;
}
public boolean contains(Object o) {
return containsKey(o);
}
public boolean remove(Object o) {
return HashMap.this.removeEntryForKey(o) != null;
}
public void clear() {
HashMap.this.clear();
}
}

其实就是返回一个私有类KeySet, 它是从AbstractSet继承而来,实现了Set接口。

再来看看for/in循环的语法

for(declaration : expression_r)
statement

在执行阶段被翻译成如下各式

for(Iterator<E> #i = (expression_r).iterator(); #i.hashNext();){
declaration = #i.next();
statement
}

因此在第一个for语句for (String appFieldDefId : appFieldDefIds) 中调用了HashMap.keySet().iterator() 而这个方法调用了newKeyIterator()

Iterator<K> newKeyIterator() {
return new KeyIterator();
}
private class KeyIterator extends HashIterator<K> {
public K next() {
return nextEntry().getKey();
}
}

所以在for中还是调用了

在第二个循环for(Entryb3de66495e219efcd34160624a719d47 entry : paraMap.entrySet())中使用的Iterator是如下的一个内部类

private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
public Map.Entry<K,V> next() {
return nextEntry();
}
}

此时第一个循环得到key,第二个循环得到HashMap的Entry

效率就是从循环里面体现出来的第二个循环此致可以直接取key和value值

而第一个循环还是得再利用HashMap的get(Object key)来取value值

现在看看HashMap的get(Object key)方法

public V get(Object key) {
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length); //Entry[] table
Entry<K,V> e = table;
while (true) {
if (e == null)
return null;
if (e.hash == hash && eq(k, e.key))
return e.value;
         e = e.next;
}
}

其实就是再次利用Hash值取出相应的Entry做比较得到结果,所以使用第一中循环相当于两次进入HashMap的Entry中

而第二个循环取得Entry的值之后直接取key和value,效率比第一个循环高。其实按照Map的概念来看也应该是用第二个循环好一点,它本来就是key和value的值对,将key和value分开操作在这里不是个好选择。

27、array(数组) 和 ArryList的使用

array([]):最高效;但是其容量固定且无法动态改变;

ArrayList:容量可动态增长;但牺牲效率;

基于效率和类型检验,应尽可能使用array,无法确定数组大小时才使用ArrayList!

ArrayList是Array的复杂版本

ArrayList内部封装了一个Object类型的数组,从一般的意义来说,它和数组没有本质的差别,甚至于ArrayList的许多方法,如Index、IndexOf、Contains、Sort等都是在内部数组的基础上直接调用Array的对应方法。

ArrayList存入对象时,抛弃类型信息,所有对象屏蔽为Object,编译时不检查类型,但是运行时会报错。

注:jdk5中加入了对泛型的支持,已经可以在使用ArrayList时进行类型检查。

从这一点上看来,ArrayList与数组的区别主要就是由于动态增容的效率问题了

28、尽量使用HashMap 和ArrayList ,除非必要,否则不推荐使用HashTable和Vector ,后者由于使用同步机制,而导致了性能的开销。

29、StringBuffer 和StringBuilder的区别:

     java.lang.StringBuffer线程安全的可变字符序列。一个类似于 String 的字符串缓冲区,但不能修改。StringBuilder。与该类相比,通常应该优先使用 java.lang.StringBuilder类,因为它支持所有相同的操作,但由于它不执行同步,所以速度更快。为了获得更好的性能,在构造 StirngBuffer 或 StirngBuilder 时应尽可能指定它的容量。当然,如果你操作的字符串长度不超过 16 个字符就不用了。 相同情况下使用 StirngBuilder 相比使用 StringBuffer 仅能获得 10%-15% 左右的性能提升,但却要冒多线程不安全的风险。而在现实的模块化编程中,负责某一模块的程序员不一定能清晰地判断该模块是否会放入多线程的环境中运行,因此:除非你能确定你的系统的瓶颈是在 StringBuffer 上,并且确定你的模块不会运行在多线程模式下,否则还是用 StringBuffer 吧。

The above is the detailed content of Detailed explanation of code in Java and optimization to improve execution efficiency. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn