Dissasembly pre and post increments (was Re: How to instantaneously
convert array of Integers into an array on int's?)
rossum wrote:
On Tue, 12 Aug 2008 22:20:38 GMT, Roedy Green
<see_website@mindprod.com.invalid> wrote:
On Tue, 12 Aug 2008 14:15:32 -0700 (PDT), Royan <romayankin@gmail.com>
wrote, quoted or indirectly quoted someone who said :
Assume I have an array of Integer objects and I need to convert them
into primitive *int* array. Another problem is that I need to this
really fast, so is there anything better then a *for* loop?
I think the fastest code you will come up with is:
int n = to.length;
for (int i=0; i<n; i++)
{
to[i] = from[i];
}
leave it to auto-un-boxing to select the optimal conversion function.
What about:
for (int i = 0, final int n = to.length; i < n; ++i) {
- scope of n is more restricted restricted so may help the compiler.
- "final" may allow the compiler to optimise more.
- pre-increment is never slower (and sometimes faster) than
post-increment. Though in this case it probably will not matter, it is
a good habit to get into.
Using the SUN javac 1.6 doest not matter. There are not differences in
the bytecode generated using post and pre increment in for loop.
I don't know why it's good habit using the pre-increment, but this is
not the first time I have heard this thing.
public class Main {
public static void main(String[] args) {
for(int i=0; i < args.length; i++) {
System.out.println(i);
}
}
public static void nonFasterMain(String[] args) {
for(int i=0; i < args.length; ++i) {
System.out.println(i);
}
}
}
C:\...>javap -classpath build\classes -c provaFor.Main
Compiled from "Main.java"
public class provafor.Main extends java.lang.Object{
public provafor.Main();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: aload_0
4: arraylength
5: if_icmpge 21
8: getstatic #2; //Field
java/lang/System.out:Ljava/io/PrintStream;
11: iload_1
12: invokevirtual #3; //Method java/io/PrintStream.println:(I)V
15: iinc 1, 1
18: goto 2
21: return
public static void nonFasterMain(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: aload_0
4: arraylength
5: if_icmpge 21
8: getstatic #2; //Field
java/lang/System.out:Ljava/io/PrintStream;
11: iload_1
12: invokevirtual #3; //Method java/io/PrintStream.println:(I)V
15: iinc 1, 1
18: goto 2
21: return
}
As others have said, if this sort of thing is required, the OP needs
to look at ways to avoid boxing/unboxing.
rossum
--
Andrea Francia
http://www.andreafrancia.it/