Chem-man17
Chem-man17

Reputation: 1770

Why is copy slower than move?

I had a big file that I'm moving about. The normal protocol in the lab is to copy it somewhere and then delete it.

I decided to change it to mv.

My question is, why is mv so much faster than cp?

To test it out I generated a file 2.7 GB in size.

time cp test.txt copy.txt

Took real 0m20.113s

time mv test.txt copy.txt

Took real 0m12.403s.

TL;DR mv was almost twice as fast as copy. Any explanations? Is this an expected result?

EDIT-

I decided to move/copy the folder to a destination other than the current folder.

time cp test.txt ../copy.txt 

and

time mv test.txt ../copy.txt

This time cp took 9.238s and mv took only 0.297s. So not what some of the answers were suggesting.

UPDATE

The answers are right. When I tried to mv the file to a different disk on the same system, mv and cp took almost the same time.

Upvotes: 2

Views: 4011

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

When you mv a file on the same filesystem, the system just has to change directory entries to reflect your renaming. Data in the file is not even read.

(same filesystem means: same directory or same directory tree/same drive, provided that source and destination directories do not traverse symlinks leading to another filesystem of course!)

When you mv a file across file systems, it has the same effect as cp + rm: no speed gain (apart from the fact that you only run one command, and consistency is guaranteed: you don't have to check if cp succeeded to perform the rm)

(older versions of mv refused to move directories across filesystems, because they only did the renaming)

Be careful, it is not equivalent. cp overwrites destination by default, whereas mv will fail renaming a file/dir into an existing file/dir.

Upvotes: 7

Related Questions