so I have somewhere between 15-300 images in a folder and I want to know which would faster:

loading all the image (file) names into an array and then randomly picking 3 distinct files using $file = opendir($folder_name)
-- OR --
loading all the image file names into the mysql database, then querying for 3 of them, say something to this effect:
SELECT filename FROM table_name ORDER BY rand() LIMIT 3
-- OR --
maybe there is something else that I can do that I didn't think of

I would try this, but I really wouldn't know how to test which one is the fastest.

When I first read your title, I assumed you wanted to know if it's faster to load images from the file system or the database, but this is not your question at all.

Well, I can't say I know for sure, but I'm comfortabe saying in your example of say 300 files in a dir or 300 filenames in a small db table, you'll get your 3 names faster with a db query. The IO required to loop over the array of filenames in the dir would have to take longer---I think. Then again, it's going to happen pretty darn fast, so unless your site is busy, I wouldn't worry about it.

I think what I'd do is this.....if I had other reasons to store the filenames in a db table, I'd store them in the db. Otherwise, I'd implement simple caching. In short, grab the filenames from the dir and store them in an array. Then serialize the array and save it to a file. For every subsequent request, first check the cache file, and if it is say, not more than 30 seconds old, use the serialized array. Otherwise, rebuild the array and save it again. This scenario may or may not make sense for your exact needs. It depends on your site usage, etc. With what I describe, the first hit--the hit that creates the cached array--takes slightly longer than just building the array of filenames. The upside is that all additional hits that use the cached array are much faster. Say you use 5 seconds as your cache TTL (Time-To-Live). Then even if you have 1000 hits per minute, your web server will not have to iterate the filenames in the dir more than once every 5 seconds.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.