Click to See Complete Forum and Search --> : can this code be optimized?
proff.hacker
Apr 16th, 2003, 08:52 PM
import java.io.*;
public class test {
public static void main (String[] arg)throws IOException{
for (int a=2;a<10;a++){
PrintWriter out = new PrintWriter(new FileWriter(""+a+".txt"));
for (int b=0;b<10;b++){
for (int c=0;c<10;c++){
for (int d=0;d<10;d++){
for (int e=0;e<10;e++){
for (int f=0;f<10;f++){
for (int g=0;g<10;g++){
out.println(""+a+b+c+d+e+f+g);
}
}
}
}
}
}
out.close();
}
System.out.println("Done");
}
}
I am wondering to know if this code can be optimized to be faster
thanks
CornedBee
Apr 17th, 2003, 05:43 AM
No, not really. If you need 8 million iterations then it doesn't matter whether it's one loop or 7.
You could probably get away with ~3 loops and some very tricky math to come to less iterations, but it takes some effort to work it out.
You could for example unroll the innermost loop, but the compiler should do that for you anyway.
Phenix
Apr 17th, 2003, 09:45 PM
Maybe declaring the ints outside of all the loops may help. It will probably be minimal (until you approach 8 million iterations). I'm not sure if primitives will start to take up memory like objects and require garbage collection. (Assuming you don't mean only the specific example you posted).
Then again, if you know the innards of how the compiler optimizes, you are way ahead of me.
Also,
for(i=0; i<someArray.length; i++)
is worse than
theLength=someArray.length;
for(i=0; i<theLength; i++)
Dillinger4
Apr 18th, 2003, 01:30 AM
So you are creating eight files filled with eight million values each? :confused: :D The only thing i could see holding the speed back would be using the print() and println() methods each of which convert their arguements to strings before outputting them.
CornedBee
Apr 18th, 2003, 02:19 AM
8 files with 1 Mio. strings.
Anyway, the slowest thing about that will still be harddisk access, so don't worry about optimizing. The only efficient optimizing that can be done is buffering output in a large buffer, but that's not under your control.
Dillinger4
Apr 18th, 2003, 12:35 PM
Corned Bee just curious, is PrintWriter buffered? From what i remember you can turn auto flushing on when a PrintWriter is created so by default auto flush should be off. So i guess in his case the stream should be flushed when close() is called rather then the stream being flushed with each subsequent call to println().
CornedBee
Apr 19th, 2003, 07:53 AM
I don't know, I don't know that much about Java.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.