简体   繁体   中英

“Caching” mySQL queries, is this an OK practice?

In my CMS, sometimes I will make redundant queries because everything is independent. Is it ok to cache queries like this?:

        global $cache_query, $cache_result;
        if(!is_array($cache_query) || !is_array($cache_result) || !in_array($q,$cache_query))
        {//The query is new. 
            $r = query_($q);
            $cache_query[] = $q;
            $cache_result[] = $r;
        }
        else
        {//The query is cached.
            foreach($cache_query as $k=>$c) // Cycle through my cached queries to find the key. Is there an getElementKey function?
                if($c == $q) {
                    if(@mysql_fetch_array($cache_result[$k])) // is the resource is still valid?
                        mysql_data_seek($cache_result[$k], 0); // rewind the pointer
                    else
                        $cache_result[$k] = query_($q); // reset the resource
                    $r = $cache_result[$k];
                    break;
                }
        }
        return $r;

OR is a better practice to just make a new query each time? $q is my query, and the function query_() returns a resource and logs if something goes wrong.

You won't get much performance improvements by caching the result resource of a database query. Database engines already provides caching on frequently executed queries, and you still have to convert that resource to an array, which is where most of the overhead comes from.

If you want to improve performance, consider prepared statements and caching the result array instead of the resource. This way you won't have to process the result over and over, but only get the result actual array from cache.

Database queries are frequently a huge portion of your execution time, so if you can cache them you should.

That said, it might be better to save them off in named variables (or named variables in an associative array). Why are you walking through the array instead of just doing:

if(isset($cache_result[$query])) {
    return $cache_result[$query];
} else {
    // not cached
}

this is a great question! There is general answer to your question.

In your case, it looks like you make a cache entry to be used for the duration of your page.

It is possible for other concurrent transactions to overwrite the database and make your cached results invalid , but usually a page is loaded very fast and the possibility of a conflict is rare enough.

Also, it looks like you're not creating a banking system, so I guess it's OK.

REMEMBER !!! Cache will be destroyed after page load, ie. it does not persist across several page loads (each page load will cost at least one query)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM