Java's behavior with int and other integer types -
this question has answer here:
- performance loop integer vs long index 2 answers
i wrote following code test how long takes java perform simple task of counting 0 huge number:
public static void main( string[] args ) { for( long k = 0 ; k <= 1000000000000000000l /* 18 zeros */ ; k++ ) ; system.out.println( "finished" ); }
i ran program , waited hours. after waiting long had no way other referring calculations estimate running time, , simple calculation convinced can take more 100 years (depending on cpu) program print message "finished"!
but after trying following code appears take time above code finish, unexpectedly saw message "finished" printed in fraction of second after ran program!
public static void main( string[] args ) { int j; for( int = 0 ; <= 1000000000 /* 9 zeros */ ; i++ ) for( j = 0 ; j <= 1000000000 /* 9 zeros */ ; j++ ) ; system.out.println( "finished" ); }
what difference of java's behavior these 2 pieces of code? there must difference between java's behavior int numbers, , behavior integer types other int.
actually think compiler optimization technique of compiler. don't think "java behavior", behavior of specific java compiler talking about.
java's own behavior specified in java language specification , for-loop specification doesn't specify optimization of either int
or long
type variables.
for current "official" compiler, may or may not optimizing long
type of incremental variables in future.
-------------------------------- optimization experiment
i ran following 2 programs:
program 1 (runs forever):
public static void main( string[] args ) { long counter = 0l; int j; for( int = 0 ; <= 1000000000 /* 9 zeros */ ; i++ ) for( j = 0 ; j <= 1000000000 /* 9 zeros */ ; j++ ) counter++; system.out.println( "finished" + counter); }
program 2 (finishes immediately):
public static void main( string[] args ) { long counter = 0l; int j; for( int = 0 ; <= 1000000000 /* 9 zeros */ ; i++ ) for( j = 0 ; j <= 1000000000 /* 9 zeros */ ; j++ ) counter++; system.out.println( "finished"); }
therefore compiler detects if there visible changes outside nested loop, if there none, skips inside loop.
Comments
Post a Comment