java编译器优化 [英] java compiler optimization

查看:100
本文介绍了java编译器优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java编译器是否足够聪明以优化下面的循环,通过提取

Is the Java compiler smart enough to optimize loop below, by extracting the

Double average = new Double( totalTime / callCount ); 

退出for循环?

public double computeSD( Set values, int callCount, long totalTime ) {
  double diffs = 0.0d; 
  for( Iterator i=values.iterator(); i.hasNext(); ) {
    double value = ( ( Double )i.next() ).doubleValue(); 
    Double average = new Double( totalTime / callCount ); 
    diffs += ( value – average.doubleValue() ) * ( value – average.doubleValue() );
  } 
  double variance = diffs / callCount;
  return Math.sqrt( variance );
}


推荐答案

Java不会也不会从循环中提取它。
任何使用'new'关键字总会导致创建一个新对象。
你最好使用 Double.valueOf()

Java will not and can not extract it from the loop. Any use of the 'new' keyword will always result in a new object being created. You would be better off using Double.valueOf()

查看<$ c的javadoc $ c> Double.valueOf(double):


返回表示指定double值的Double实例。如果不需要新的Double实例,通常应优先使用此方法,而不是构造函数Double(double),因为此方法可能通过缓存经常请求的值来显着提高空间和时间性能。

"Returns a Double instance representing the specified double value. If a new Double instance is not required, this method should generally be used in preference to the constructor Double(double), as this method is likely to yield significantly better space and time performance by caching frequently requested values."

如果您使用此方法,它将每次返回相同的对象,从而减少创建的对象数量并提高性能。

If you used this method it would return the same object every time, thus reducing the number of objects created and increasing performance.

然而,使用 valueOf 仍然不是你的答案!

However, using valueOf is still not the answer for you!

valueOf 仍然是一个方法调用,并且方法调用不会被优化掉。它将在循环的每次迭代中调用 valueOf 。查看您的方法并计算方法调用。现在它是6,包括 hasNext new Double ,这类似于方法调用。这些都会每次都发生,没有java优化会改变它。你最好从重构中删除尽可能多的方法调用。

valueOf is still a method call, and method calls do not get optimized away. It will call valueOf every iteration of the loop. Look through your method and count the method calls. Right now it is 6, including hasNext and new Double, which is similar to a method call. These will all happen every time, and no java optimization will change that. You are better off refactoring to remove as many method calls as possible from the loop.

这篇关于java编译器优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆