How many times does a compiled query have to recompile during the lifecycle of an application?

307 Views Asked by At

In a website, if I have a class:

public class Provider
{
    static readonly Func<Entities, IEnumerable<Tag>> AllTags =
        CompiledQuery.Compile<Entities, IEnumerable<Tag>>
        (
            e => e.Tags
        );

    public IEnumerable<Tag> GetAll()
    {
        using (var db = new Entities())
        {
            return AllTags(db).ToList();
        }
    }
}

In a page I have:

protected void Page_Load(object sender, EventArgs ev)
{
    (new Provider()).GetAll();
}

How many times the query will be compiled? Every time the page loads...? Once in the application...?

5

There are 5 best solutions below

0
On BEST ANSWER

Seeing it is compiled. I would say once. Why would it need to be recompiled? Isn't that the point of compiled queries?

Given the compiled query is static, once per application instance/lifetime. Note: Lifetimes may overlap.

0
On

since it is a static member, once when class is loaded in app domain.

0
On

I'd say once per AppDomain, since it's a static variable.

1
On

http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx#Y696

"Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called."

So it will compile at most each time the page is loaded. Since your class doesn't have a static constructor, it shouldn't compile until you actually access the static member. (According to MSDN.)

However, does that compile? It appears you are trying to load a static member from an instantiated class.

0
On

If you define your AllTags query this way it will be compiled only once. Check this blog post about compiled queries in Web applications and web services by Julie Lerman.