would love your thoughts on this one.
I am using jQuery autocomplete in a ASP.NET MVC application to retrieve a list of records from a database - I would like to know if there is a better way than the way I am currently doing it - as follows:
Here is the jQuery (I am calling an action method 'GetRecordByName' with the autocomplete)
$('#tb_name').autocomplete({
source: 'Home/GetRecordByName',
minLength: 1, delay: 0,
select: function (event, ui) {
// do stuff
}
});
On the back end, I am using Linq to Entities in the method to obtain the results from the database:
public JsonResult GetRecordByName(string term)
{
var data = records
.Where(dr => dr.Key.StartsWith(term))
.Select(dr => new { dr, value = dr.Key })
.Take(5);
return Json(data, JsonRequestBehavior.AllowGet);
}
Currently, it's running a bit slow (~ 1-2 seconds). Basically, the DB has tens of thousands of records in it and each time you type a character in the text box, the app hits the database. I can set it to 2 or 3 characters, but it doesn't change the speed, nor do I want to require that many characters.
I have an idea on how to optimize it: On pageload, get all possible results from the DB and send it to the client (via a hidden input or a javascript data structure), and have autocomplete use that client side data as the source. I'm sure that would be lightning fast, but it seems weird to me - are there are any drawbacks to doing it that way?
Are there any other ways to achieve a faster autocomplete?
UPDATE: Ok, apparently the problem was the way I was constructing my EF call. The EF call off of 'records' ultimately wasn't constructing a WHERE clause in the sql query; it was getting the whole table each time, and then the linq methods were going off that already-enumerated mass of data - this was occurring each time a letter was typed - causing the slowdown. Doh! I moved the .Where method to the data repository layer where it is enumerating after the where filters the results, and returning a Dictionary - seems to work great now. Thanks for all your help! I marked the most helpful answer which helped me investigate the issue.
As far as the Flickr solution / bringing the whole set of data to the client, I still feel like that's weird / overkill, but I'm sure it's warranted with certain large datasets. Also will be looking more into OutputCache for other things.
Thanks again!