java编译器对于循环进行了真正的编译优化吗?
此文章只是用来在java编译器进行循环化方面的验证,本文是有感而发,并希望求得大家的分析结果,这里引用了一位网友的话(没有人身攻击的色彩):
///////////////////////////
对于Vector v=new Vector()若v中包含了10000个对象,我们进行一个loop如下
for(int I=0; I<v.size(); I++) { System.out.println("testing..."); }
大家一定会用如下的写法吧
int size = v.size(); for(int I=0; I<size; I++) { System.out.println("testing..."); }
///////////////////////////
但有些网友说(只是为了说明问题而已,无攻击色彩):
不能用完全解释语言过程来理解Java,v.size()在循环中并没有被调用10000次,因为,编译的循环优化会对其进行优化,
因此,实际运行时只运行一次,和用初始化v.size()的程序效率一样。这是很早的编译优化机制。
大家肯定这种说易做图确吗?我不太赞同,很简单地可以用一个test作难证:
一个类Vector的类TetstObj.java
-
- public class TestObj {
- int count=0;
- public TestObj() {
- count+=5;
- }
- public int size(){
- System.out.println("size="+count);
- return count;
- }
- }
测试类:test.java
-
- public class test{
- public test(){}
- public static void main(String[] args){
- TestObj similarVector=new TestObj();
- for(int i=1;i<similarVector.size();i++){
- //do something
- }
- }
- }
结果还是5个size=1的打印结果.
size=5
size=5
size=5
size=5
size=5
大家也可以分析一下java.util.Vector这个类(下面摘录Vector的部分源码)
例如只以一个insert对象而言:
-
- /**
- * Returns the number of components in this vector.
- *
- * @return the number of components in this vector.
- */
- protected int elementCount;
- /**
- * Inserts the specified object as a component in this vector at the
- * specified <code>index</code>. Each component in this vector with
- * an index greater or equal to the specified <code>index</code> is
- * shifted upward to have an index one greater than the value it had
- * previously. <p>
- *
- * The index must be a value greater than or equal to <code>0</code>
- * and less than or equal to the current size of the vector. (If the
- * index is equal to the current size of the vector, the new element
- * is appended to the Vector.)<p>
- *
- * This method is identical in functionality to the add(Object, int) method
- * (which is part of the List inte易做图ce). Note that the add method reverses
- * the order of the parameters, to more closely match array usage.
- *
- * @param obj the component to insert.
- * @param index where to insert the new component.
- * @exception ArrayIndexOutOfBoundsException if the index was invalid.
- * @see #size()
- * @see #add(int, Object)
- * @see List
- */
- public synchronized void insertElementAt(Object obj, int index) {
- modCount++;
- if (index >= elementCount + 1) {
- throw new ArrayIndexOutOfBoundsException(
补充:软件开发 , Java ,