Why calling flush on each file.write not impact on performance?

I heard flush can impact on performance on each call,
why isn't any impact on bellow code ??

both run in near sometime and
sometimes flush on each iteration run faster

let now = Instant::now();
    // ============================================

    for _ in 0..10_000 {
        let _ = log.write(&mut b"Rusttttttt".to_vec());   
        let _ = log.flush();
    }
    // ============================================
    let nnow = Instant::now();
    println!("==> {:?}", nnow.duration_since(now));
    
let now = Instant::now();
    // ============================================

    for _ in 0..10_000 {
        let _ = log.write(&mut b"Rusttttttt".to_vec());   
    }

    let _ = log.flush();

    // ============================================
    let nnow = Instant::now();
    println!("==> {:?}", nnow.duration_since(now));
    

What type is Log. Some types have a noop for flush ( std::io::Cursor for example). Also you're needlessly allocating a Vector every loop which reduces the impact of any overhead of flush (A flush to disk should be far worse even then). Assuming log is using the std::io::Write trait, you can get rid of the &mut and to_vec. Also you typically should use write_all instead of write, especially if you ignore the result.

1 Like

Note that File is not buffered, so it doesn't actually have anything to flush. You can wrap it in a BufWriter if you do want buffering, but don't bother if you're just going to flush every write anyway. :slight_smile:

6 Likes

flush of io::Write is not like fsync. It doesn't have to do anything beyond what regular write does. If the data has already been sent to be written by previous write calls, it is a no-op.

3 Likes

thanks, log is this

There is File::sync_all for that though.

The type of log here is this https://docs.rs/advisory-lock/0.2.0/advisory_lock/struct.AdvisoryFileLock.html

Which actually derefs (and derefmuts) to std::fs::File, so I don't see what that type is supposed to do.

@DanyalMh that benchmark means nothing

1 Like