Why locate is faster than find? [duplicate]
I was looking for a file in my source and tried both locate and find. Surprisingly locate was searching in entire machine and was faster than find, which was searching only in current directory and sub directories.
Here are my shell commands for both:
find . -name vendorsetup.sh # takes 50 seconds to search all files in curren -sub directories.
locate vendorsetup.sh # takes 20 seconds to search file in whole machine.
Why this?
Solution 1:
locate
uses a database and periodically does an inventory of your file system. The database is optimized for searching. find
needs to traverse the whole subdirectory, which is pretty fast, but not as fast as locate.
Solution 2:
About Locate :
Locate uses an index that stores in
/var/lib/slocate/
, that is updated by a nightly Cron job. This nightly job typically runs at about 1AM or 2AM of local time, and completely scans your entire system (including all connected drives). The resulting index is simply a list of filenames.Search will be so fast because of already indexing done to every element in filesystem
But find
is not like so,
everytime it will consider the search as fresh search and no storing of any cache of file location.
so it will take time to find.
hope that helps.