0

I have this code that returns JSon for autocomplete.

public ActionResult AutocompleteCompany(string term)
{
    var model = CacheObjects.Companies
                            .Where(x => x.CompanyName.Contains(term))
                            .Select(x => new
                            {
                                label = x.CompanyName,
                                id = x.CompanyId
                            });
    return this.Json(model, JsonRequestBehavior.AllowGet); 
}

There is a performance issue here because I am newing up the label and id. There must be another way of doing this which is faster?

EDIT - it is probably the Contains clause that is the performance issue here

Xaruth
  • 4,034
  • 3
  • 19
  • 26
arame3333
  • 9,887
  • 26
  • 122
  • 205

1 Answers1

1

As your concern seems to be about the overhead/performance of Anonymous Types, in terms of performance, anonymous types are similar to other normal types. As behind the scenes the CLR compiles them down to normal types (just with an unspeakable name).

See here: Performance of anonymous types in C#

EDIT: In terms of what you're doing, selecting specific properties from an object for a strongly typed solution I cannot see any way to improve on it.

Please see a similar question here (in terms of pulling multiple properties from an object using LINQ) all answers provided use anonymous types as this is the preferred solution: Select Multiple Fields from List in Linq

Depending on your client side implementation there are a number of things you could do (if you're not already) depending on the data you acquire (both in terms of the amount plus the frequency in which it updates) you could always have it all pulled into a JSON object client side when the page loads and query it with Javascript for your autocomplete functionality (or you could cache it server side and still use LINQ). Also you could make it so that the autocomplete function is not called after each keystroke in your input box but instead wait 2 seconds or so before making the call for the objects.

Community
  • 1
  • 1
BenM
  • 4,218
  • 2
  • 31
  • 58
  • Not really an answer to the original question, but an interesting reference, confirming that the performance of newing up anonymous types is no different to class types. – arame3333 Mar 05 '14 at 09:31
  • It is probably the Contains clause then – arame3333 Mar 05 '14 at 10:20
  • 1
    I've added a couple of design considerations to my answer in case any of them could be applied to your solution. – BenM Mar 05 '14 at 10:27