This article is only used to verify the java compiler in a cyclical manner. This article is a post, and I hope to get your analysis results. Here I reference a netizen (without personal attacks ):
///////////////////////////
If Vector v = new Vector () contains 10000 objects, we perform the following loop:
For (int I = 0; I <v. size (); I ++) {System. out. println ("testing ...");}
You must write the following code:
Int size = v. size (); for (int I = 0; I <size; I ++) {System. out. println ("testing ...");}
///////////////////////////
But some netizens said (just to illustrate the problem, there is no attack color ):
Java cannot be fully interpreted. v. size () is not called 10000 times in a loop, because the compiled loop optimization will optimize it,
Therefore, the program runs only once, which is the same as the program that initializes v. size. This is an early compilation optimization mechanism.
Are you sure this is correct? I don't agree with it. It's easy to use a test to prove it:
A Vector-like TetstObj. java
- Public ClassTestObj {
- IntCount = 0;
- PublicTestObj (){
- Count + = 5;
- }
- Public IntSize (){
- System. Out. println ("size =" + count );
- ReturnCount;
- }
- }
Test class: test. java
- PublicClassTest {
- PublicTest (){}
- Public Static VoidMain (String[] Args ){
- TestObj similarVector =NewTestObj ();
- For(IntI = 1; I <similarVector. size (); I ++ ){
- // Do something
- }
- }
- }
The result is still printed with 5 size = 1.
Size = 5
Size = 5
Size = 5
Size = 5
Size = 5
You can also analyze the java. util. Vector class (the source code of the Vector is extracted below)
For example, if only one insert object is used:
- /**
- * Returns the number of components in this vector.
- *
- * @ Return the number of components in this vector.
- */
- Protected IntElementCount;
- /**
- * Inserts the specified object as a component in this vector at
- * Specified <code> index </code>. Each component in this vector
- * 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
- * Previusly. <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
- * 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 interface). 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 VoidInsertElementAt (ObjectObj,IntIndex ){
- ModCount ++;
- If(Index> = elementCount + 1 ){
- Throw New ArrayIndexOutOfBoundsException(