简体   繁体   中英

Caching jquery autocomplete data in memory

If I have a table that contains country/state/province/city/latitude/longitude that has a few thousand records and I'm using it to autocomplete a field on my search page, whats the best way to cache this data into memory to make the site a little faster? Should I put all the table data into a global app cache or is there a better way?

Populate your autocomplete with the response from an ajax request. Just call a method on your controller and return a JsonResult. This will allow you to take advantage of the output cache attribute which can be applied to the method.

    [OutputCache(Duration=1000, VaryByParam="*", Location="Any")]
    public JsonResult AutoComplete(string term)
    {
        var result = //Database query
        return Json(result, JsonRequestBehavior.AllowGet);
    }

This will cache the results on the server or client and will create a new cache instance for each search parameter passed over to the method.

You can even use a cache profile with the output cache which will allow you to have the caching options in the webconfig and allow you to easily update in future.

Hope this helps you.

There are various options, and it's too complex a problem to say which one (if any) is better without knowing more about your use case.

Server-side, the code you use to retrieve the options from the database could use a MemoryCache to pull it from the cache if it's there.

var records = MemoryCache.Default.Get("LocationRecords");
if(records == null)
{
    records = GetRecords(); // <-- the method you're using now to retrieve the records

    // Change this based on how long you want to cache things for
    var expiration = DateTimeOffset.Now.AddHours(6);

    MemoryCache.Default.Add("LocationRecords", expiration);
}
return records;

You could also set up the client-side to load the options themselves using an AJAX GET request, and have the server tell the client to cache the information it sends back, so that any given user's browser will only ever ask the server for the data once.

In either of these approaches, you need to spend time thinking about how long the data is good for, and come up with a good caching/cache-clearing/cache-busting strategy.

Should I put all the table data into a global app cache or is there a better way?

Again, it depends a lot on your situation. I personally prefer to create a new MemoryCache instance that I keep as a static variable on each of my repository types. That way I can avoid the possibility of key collisions, and easily clear out one cache at a time without affecting the others. But if your application is small, simply using MemoryCache.Default may be just fine.

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