As you know we have several tools in java for writing data into streams.
In this sample code I have compared them by runtime.
Can somebody explain it exactly? Thanks.
Here is the code:
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
public class IOtests
{
public static void main(String[] args) throws Exception
{
char[] chars = new char[100];
byte[] bytes = new byte[100];
for (int i = 0; i < 100; i++)
{
chars[i] = (char) i;
bytes[i] = (byte) i;
}
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(
"output.txt"));
long a = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
for (char j : chars)
out.write(j);
System.out.println("OutputStreamWriter writing characters: "
+ (System.currentTimeMillis() - a));
out = new OutputStreamWriter(new FileOutputStream("output.txt"));
a = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
for (byte j : bytes)
out.write(j);
System.out.println("OutputStreamWriter writing bytes: "
+ (System.currentTimeMillis() - a));
PrintStream out1 = new PrintStream("output.txt");
a = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
for (char j : chars)
out1.write(j);
System.out.println("PrintStream writing characters: "
+ (System.currentTimeMillis() - a));
out1 = new PrintStream("output.txt");
a = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
for (byte j : bytes)
out1.write(j);
System.out.println("PrintStream writing bytes: "
+ (System.currentTimeMillis() - a));
PrintWriter out2 = new PrintWriter("output.txt");
a = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
for (char j : chars)
out2.write(j);
System.out.println("PrintWriter writing characters: "
+ (System.currentTimeMillis() - a));
out1 = new PrintStream("output.txt");
a = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
for (byte j : bytes)
out2.write(j);
System.out.println("PrintWriter writing bytes: "
+ (System.currentTimeMillis() - a));
}
}
Results:
OutputStreamWriter writing characters: 4141
OutputStreamWriter writing bytes: 3546
PrintStream writing characters: 86516
PrintStream writing bytes: 70484
PrintWriter writing characters: 938
PrintWriter writing bytes: 2484
Note that all times are in milliseconds.
I've reduced your question to its essence:
Notes:
write(int)
. Therefore it makes no difference whether you are using bytes or chars;FileWriter
and aFileOutputStream
because all other cases boil down to these two;Now, when you run this, you'll get output like the following:
So, what's the lesson?
StreamEncoder
which is itself buffered;FileOutputStream
is not buffered;Good practices demand that you always do buffered writing: either using buffered sinks, or maintaining an explicit buffer on your side.