W
W
WTFAYD2017-02-01 19:54:16
Java
WTFAYD, 2017-02-01 19:54:16

Why does BufferedWriter write slower than FileWriter?

I need to measure the performance of buffered and unbuffered writes to a file and compare them. I wrote this code:

String text = "ABCDEF";
    long startTime, stopTime;
    
    BufferedWriter w = new BufferedWriter(new FileWriter("file1.txt"));
    startTime = System.nanoTime();
    w.write(text);
    w.close();
    stopTime = System.nanoTime();
    print(stopTime - startTime); // 1
    
    FileWriter w1 = new FileWriter("file1.txt");
    startTime = System.nanoTime();
    w1.write(text);
    w1.close();
    stopTime = System.nanoTime();
    print(stopTime - startTime); // 2

The book says that buffered operations are faster than unbuffered ones, but in fact it turns out that the first number (marked with a comment as 1) is larger than the second number. If I swap them (measure the unbuffered record first), the situation is still the same - the first number is greater than the second. Tell me what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Moseychuk, 2017-02-02
@fshp

Tell me what am I doing wrong?

Write benchmarks.

D
Dmitry, 2017-02-04
@dsv

Perhaps you need to "warm up" the jvm first. Run your code several times in a loop, see how the measurements change in each loop, try discarding the first n-cycles.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question