7

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?

2
  • 1
    Mind you: try that with a file you just created and locate will NOT find it. find will find it ;) (locate is fast but less accurate than find).
    – Rinzwind
    Jul 22, 2014 at 12:00
  • 20 seconds for a 'locate' lookup sounds pretty slow. On my (rather slow) system it takes between 1-2 seconds to find anything: time locate nonexisting_file locate nonexisting_file 1.46s user 0.01s system 99% cpu 1.483 total
    – Popup
    Jul 22, 2014 at 15:59

2 Answers 2

11

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.

2
  • 1
    Also, thanks to the periodic inventory (updatedb), the results won't be quite as recent. This would succeed: touch someuniquefilename; find / -name someuniquefilename, but this would probably fail: touch someuniquefilename; locate someuniquefilename
    – Plutor
    Jul 22, 2014 at 17:00
  • however, you can run sudo updatedb and then locate will find new files
    – Zanna
    Jun 17, 2016 at 6:10
3

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.

3
  • 3
    Hasn't slocate been replaced by mlocate? Also, AFAIK it does not scan connected drives by default, in fact the standard /etc/updatedb.conf file specifically excludes paths like /media and remote filesystems such as NFS and SAMBA. Jul 22, 2014 at 12:00
  • Also, I don't know about you, but my desktop is rarely online at 2am and yet locate still seems to be updated...
    – Benubird
    Jul 22, 2014 at 15:28
  • I believe the locate database is also updated on startup Jul 22, 2014 at 16:26

Not the answer you're looking for? Browse other questions tagged .