I observed huge difference between following two scenarios for copying a file:

1. Copying a file into a new file.
2. Copying a file in an existing file
and overwriting it.

I expect both operations take the same amount of time to complete. But the first scenario is much faster in practice. I tried this on two different file systems, getting the same result. Any idea why the first scenario is much faster?

**Example in Linux:**

```
$ dd bs=1024 count=1000000 if=/dev/zero of=dummyfile.txt
1000000+0 records in
1000000+0 records out
1024000000 bytes (1.0 GB) copied, 7.45639 s, 137 MB/s
$ while [ "1" == "1" ]; do time cp dummyfile.txt dummyfile2.txt ; rm dummyfile2.txt ; done

real    0m0.850s
user    0m0.003s
sys     0m0.847s

real    0m0.778s
user    0m0.000s
sys     0m0.776s

real    0m0.775s
user    0m0.004s
sys     0m0.772s

real    0m0.775s
user    0m0.003s
sys     0m0.770s

real    0m0.776s
user    0m0.008s
sys     0m0.766s
^C
$ rm dummyfile2.txt -f
$ while [ "1" == "1" ]; do time cp dummyfile.txt dummyfile2.txt ;  done

real    0m0.839s
user    0m0.003s
sys     0m0.834s

real    0m6.056s
user    0m0.005s
sys     0m1.683s

real    0m6.614s
user    0m0.002s
sys     0m1.405s

real    0m6.858s
user    0m0.003s
sys     0m1.436s

```

**EDIT:** test is performed on an SSD disk. I observed the same trend on HDD, but the gap is lower than SDD (2-3X). Following page explains why SSDs are much slower than HDDs in overwrite:

[Trim (computing) Wikipedia page](http://en.wikipedia.org/wiki/Trim_(computing))
['https://superuser.com/questions/865710', 'https://superuser.com', 'https://superuser.com/users/173093/']
I believe it's ext4's `auto_da_alloc` behavior that makes this difference. 
[see ext4 kernel doc](https://www.kernel.org/doc/html/latest/admin-guide/ext4.html)

@Zaboj Campula 's answer show us that close() a truncated file would block until written data got "forced to disk". ext4 auto detected this replace-by-truncate use pattern.

likewise, if you rename (mv) your new created file as some existing file, you will find that the rename() syscall will block for some time. that's the replace-by-rename use pattern.
Overwriting takes a seek operation... 

The file's permissions must be read in order to know if you can overwrite it(which may or may not be an issue depending on your file system). 
Also the file must be truncated.

This requires the drive to seek to the position where the file is..

Copying into a new file generates new permissions and uses the closest available free blocks to write and does not need a seek.

Look into "copy-on-write" file systems(Like ZFS) that don't do this..