Which way of implemeting conditions in Entity Framework has a better performance?












0















When I want to do some validation stuff on database entities, I can think of two ways:



1: Retrive the field value and then do the calculations in the application:



if (dbContext.Coupons.Where(c=> c.Id == couponId).Select(c=> c.ExpirationDate).Single() <= DateTime.Now)


2: Do the calculations in the query (in 'Select()' method) and then retrive the result:



if (dbContext.Coupons.Where(c=> c.Id == couponId).Select(c=> c.ExpirationDate <= DateTime.Now).Single())









share|improve this question

























  • Wouldn't it be much faster, if you just made a benchmark with some data? Then you would know which one is better, performance wise

    – sLw
    Nov 21 '18 at 7:25











  • If your couponId is primary key (well, according your where->select->single - it is), instead of .Where(c=> c.Id == couponId) you can do Coupons.Find(couponId).ExpirationDate <= DateTime.Now.

    – SeM
    Nov 21 '18 at 7:28








  • 1





    Race your horses ericlippert.com/2012/12/17/performance-rant

    – S.Akbari
    Nov 21 '18 at 7:30













  • @SeM Find method retrives the whole row from the database and actually kills the performace.

    – Amir Hossein Ahmadi
    Nov 21 '18 at 7:31











  • @AmirHosseinAhmadi it depends whether your row exists in cache or not.

    – SeM
    Nov 21 '18 at 7:44
















0















When I want to do some validation stuff on database entities, I can think of two ways:



1: Retrive the field value and then do the calculations in the application:



if (dbContext.Coupons.Where(c=> c.Id == couponId).Select(c=> c.ExpirationDate).Single() <= DateTime.Now)


2: Do the calculations in the query (in 'Select()' method) and then retrive the result:



if (dbContext.Coupons.Where(c=> c.Id == couponId).Select(c=> c.ExpirationDate <= DateTime.Now).Single())









share|improve this question

























  • Wouldn't it be much faster, if you just made a benchmark with some data? Then you would know which one is better, performance wise

    – sLw
    Nov 21 '18 at 7:25











  • If your couponId is primary key (well, according your where->select->single - it is), instead of .Where(c=> c.Id == couponId) you can do Coupons.Find(couponId).ExpirationDate <= DateTime.Now.

    – SeM
    Nov 21 '18 at 7:28








  • 1





    Race your horses ericlippert.com/2012/12/17/performance-rant

    – S.Akbari
    Nov 21 '18 at 7:30













  • @SeM Find method retrives the whole row from the database and actually kills the performace.

    – Amir Hossein Ahmadi
    Nov 21 '18 at 7:31











  • @AmirHosseinAhmadi it depends whether your row exists in cache or not.

    – SeM
    Nov 21 '18 at 7:44














0












0








0


3






When I want to do some validation stuff on database entities, I can think of two ways:



1: Retrive the field value and then do the calculations in the application:



if (dbContext.Coupons.Where(c=> c.Id == couponId).Select(c=> c.ExpirationDate).Single() <= DateTime.Now)


2: Do the calculations in the query (in 'Select()' method) and then retrive the result:



if (dbContext.Coupons.Where(c=> c.Id == couponId).Select(c=> c.ExpirationDate <= DateTime.Now).Single())









share|improve this question
















When I want to do some validation stuff on database entities, I can think of two ways:



1: Retrive the field value and then do the calculations in the application:



if (dbContext.Coupons.Where(c=> c.Id == couponId).Select(c=> c.ExpirationDate).Single() <= DateTime.Now)


2: Do the calculations in the query (in 'Select()' method) and then retrive the result:



if (dbContext.Coupons.Where(c=> c.Id == couponId).Select(c=> c.ExpirationDate <= DateTime.Now).Single())






c# sql entity-framework linq-to-sql linq-to-entities






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 7:25







Amir Hossein Ahmadi

















asked Nov 21 '18 at 7:24









Amir Hossein AhmadiAmir Hossein Ahmadi

170419




170419













  • Wouldn't it be much faster, if you just made a benchmark with some data? Then you would know which one is better, performance wise

    – sLw
    Nov 21 '18 at 7:25











  • If your couponId is primary key (well, according your where->select->single - it is), instead of .Where(c=> c.Id == couponId) you can do Coupons.Find(couponId).ExpirationDate <= DateTime.Now.

    – SeM
    Nov 21 '18 at 7:28








  • 1





    Race your horses ericlippert.com/2012/12/17/performance-rant

    – S.Akbari
    Nov 21 '18 at 7:30













  • @SeM Find method retrives the whole row from the database and actually kills the performace.

    – Amir Hossein Ahmadi
    Nov 21 '18 at 7:31











  • @AmirHosseinAhmadi it depends whether your row exists in cache or not.

    – SeM
    Nov 21 '18 at 7:44



















  • Wouldn't it be much faster, if you just made a benchmark with some data? Then you would know which one is better, performance wise

    – sLw
    Nov 21 '18 at 7:25











  • If your couponId is primary key (well, according your where->select->single - it is), instead of .Where(c=> c.Id == couponId) you can do Coupons.Find(couponId).ExpirationDate <= DateTime.Now.

    – SeM
    Nov 21 '18 at 7:28








  • 1





    Race your horses ericlippert.com/2012/12/17/performance-rant

    – S.Akbari
    Nov 21 '18 at 7:30













  • @SeM Find method retrives the whole row from the database and actually kills the performace.

    – Amir Hossein Ahmadi
    Nov 21 '18 at 7:31











  • @AmirHosseinAhmadi it depends whether your row exists in cache or not.

    – SeM
    Nov 21 '18 at 7:44

















Wouldn't it be much faster, if you just made a benchmark with some data? Then you would know which one is better, performance wise

– sLw
Nov 21 '18 at 7:25





Wouldn't it be much faster, if you just made a benchmark with some data? Then you would know which one is better, performance wise

– sLw
Nov 21 '18 at 7:25













If your couponId is primary key (well, according your where->select->single - it is), instead of .Where(c=> c.Id == couponId) you can do Coupons.Find(couponId).ExpirationDate <= DateTime.Now.

– SeM
Nov 21 '18 at 7:28







If your couponId is primary key (well, according your where->select->single - it is), instead of .Where(c=> c.Id == couponId) you can do Coupons.Find(couponId).ExpirationDate <= DateTime.Now.

– SeM
Nov 21 '18 at 7:28






1




1





Race your horses ericlippert.com/2012/12/17/performance-rant

– S.Akbari
Nov 21 '18 at 7:30







Race your horses ericlippert.com/2012/12/17/performance-rant

– S.Akbari
Nov 21 '18 at 7:30















@SeM Find method retrives the whole row from the database and actually kills the performace.

– Amir Hossein Ahmadi
Nov 21 '18 at 7:31





@SeM Find method retrives the whole row from the database and actually kills the performace.

– Amir Hossein Ahmadi
Nov 21 '18 at 7:31













@AmirHosseinAhmadi it depends whether your row exists in cache or not.

– SeM
Nov 21 '18 at 7:44





@AmirHosseinAhmadi it depends whether your row exists in cache or not.

– SeM
Nov 21 '18 at 7:44












2 Answers
2






active

oldest

votes


















1














I suggest, every validation, filter or process do within linq or process that take value from db (SQL Query) or object.



for example :



if you have 10 datas in table and you use the second way, the app will import all data into local memory and filtered inside app.



but if you use the first way, the app only import the datas that already filtered (example only 4 datas after filter process)



if your datas is more than 10K maybe you'll see the different






share|improve this answer































    0














    This will give you best performance.



    if (dbContext.Coupons.Any(c => c.Id == couponId && c.ExpirationDate <= DateTime.Now))





    share|improve this answer
























    • What are the differences between your approach and my second approach? (They both return a boolean and do the same thing)

      – Amir Hossein Ahmadi
      Jan 6 at 14:02











    • @AmirHosseinAhmadi Using Where () creates an iterator which adds performance impact, whereas using any () with predicate can perform its task without an iterator. In additional, You will get an exception if your condition will find more than 1 record.

      – AGH
      Jan 8 at 5:31











    • First of all, "Where()" method creates an IQueryable which is going to be translated to SQL, and in both of these two ways, we have the same generated SQL (not exactly the same, there is a slight difference). Second of all, there's definitely only 1 element in the sequence because the condition is based on the primary key.

      – Amir Hossein Ahmadi
      Jan 8 at 13:51













    • @AmirHosseinAhmadi As far as I know, Using any() Linq is generate SQL query with exists and return true or false, so there is no require extra condition as you mention in your question.

      – AGH
      Jan 9 at 5:47













    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53407082%2fwhich-way-of-implemeting-conditions-in-entity-framework-has-a-better-performance%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    I suggest, every validation, filter or process do within linq or process that take value from db (SQL Query) or object.



    for example :



    if you have 10 datas in table and you use the second way, the app will import all data into local memory and filtered inside app.



    but if you use the first way, the app only import the datas that already filtered (example only 4 datas after filter process)



    if your datas is more than 10K maybe you'll see the different






    share|improve this answer




























      1














      I suggest, every validation, filter or process do within linq or process that take value from db (SQL Query) or object.



      for example :



      if you have 10 datas in table and you use the second way, the app will import all data into local memory and filtered inside app.



      but if you use the first way, the app only import the datas that already filtered (example only 4 datas after filter process)



      if your datas is more than 10K maybe you'll see the different






      share|improve this answer


























        1












        1








        1







        I suggest, every validation, filter or process do within linq or process that take value from db (SQL Query) or object.



        for example :



        if you have 10 datas in table and you use the second way, the app will import all data into local memory and filtered inside app.



        but if you use the first way, the app only import the datas that already filtered (example only 4 datas after filter process)



        if your datas is more than 10K maybe you'll see the different






        share|improve this answer













        I suggest, every validation, filter or process do within linq or process that take value from db (SQL Query) or object.



        for example :



        if you have 10 datas in table and you use the second way, the app will import all data into local memory and filtered inside app.



        but if you use the first way, the app only import the datas that already filtered (example only 4 datas after filter process)



        if your datas is more than 10K maybe you'll see the different







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 7:35









        LemonsLemons

        47110




        47110

























            0














            This will give you best performance.



            if (dbContext.Coupons.Any(c => c.Id == couponId && c.ExpirationDate <= DateTime.Now))





            share|improve this answer
























            • What are the differences between your approach and my second approach? (They both return a boolean and do the same thing)

              – Amir Hossein Ahmadi
              Jan 6 at 14:02











            • @AmirHosseinAhmadi Using Where () creates an iterator which adds performance impact, whereas using any () with predicate can perform its task without an iterator. In additional, You will get an exception if your condition will find more than 1 record.

              – AGH
              Jan 8 at 5:31











            • First of all, "Where()" method creates an IQueryable which is going to be translated to SQL, and in both of these two ways, we have the same generated SQL (not exactly the same, there is a slight difference). Second of all, there's definitely only 1 element in the sequence because the condition is based on the primary key.

              – Amir Hossein Ahmadi
              Jan 8 at 13:51













            • @AmirHosseinAhmadi As far as I know, Using any() Linq is generate SQL query with exists and return true or false, so there is no require extra condition as you mention in your question.

              – AGH
              Jan 9 at 5:47


















            0














            This will give you best performance.



            if (dbContext.Coupons.Any(c => c.Id == couponId && c.ExpirationDate <= DateTime.Now))





            share|improve this answer
























            • What are the differences between your approach and my second approach? (They both return a boolean and do the same thing)

              – Amir Hossein Ahmadi
              Jan 6 at 14:02











            • @AmirHosseinAhmadi Using Where () creates an iterator which adds performance impact, whereas using any () with predicate can perform its task without an iterator. In additional, You will get an exception if your condition will find more than 1 record.

              – AGH
              Jan 8 at 5:31











            • First of all, "Where()" method creates an IQueryable which is going to be translated to SQL, and in both of these two ways, we have the same generated SQL (not exactly the same, there is a slight difference). Second of all, there's definitely only 1 element in the sequence because the condition is based on the primary key.

              – Amir Hossein Ahmadi
              Jan 8 at 13:51













            • @AmirHosseinAhmadi As far as I know, Using any() Linq is generate SQL query with exists and return true or false, so there is no require extra condition as you mention in your question.

              – AGH
              Jan 9 at 5:47
















            0












            0








            0







            This will give you best performance.



            if (dbContext.Coupons.Any(c => c.Id == couponId && c.ExpirationDate <= DateTime.Now))





            share|improve this answer













            This will give you best performance.



            if (dbContext.Coupons.Any(c => c.Id == couponId && c.ExpirationDate <= DateTime.Now))






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 29 '18 at 9:57









            AGHAGH

            1608




            1608













            • What are the differences between your approach and my second approach? (They both return a boolean and do the same thing)

              – Amir Hossein Ahmadi
              Jan 6 at 14:02











            • @AmirHosseinAhmadi Using Where () creates an iterator which adds performance impact, whereas using any () with predicate can perform its task without an iterator. In additional, You will get an exception if your condition will find more than 1 record.

              – AGH
              Jan 8 at 5:31











            • First of all, "Where()" method creates an IQueryable which is going to be translated to SQL, and in both of these two ways, we have the same generated SQL (not exactly the same, there is a slight difference). Second of all, there's definitely only 1 element in the sequence because the condition is based on the primary key.

              – Amir Hossein Ahmadi
              Jan 8 at 13:51













            • @AmirHosseinAhmadi As far as I know, Using any() Linq is generate SQL query with exists and return true or false, so there is no require extra condition as you mention in your question.

              – AGH
              Jan 9 at 5:47





















            • What are the differences between your approach and my second approach? (They both return a boolean and do the same thing)

              – Amir Hossein Ahmadi
              Jan 6 at 14:02











            • @AmirHosseinAhmadi Using Where () creates an iterator which adds performance impact, whereas using any () with predicate can perform its task without an iterator. In additional, You will get an exception if your condition will find more than 1 record.

              – AGH
              Jan 8 at 5:31











            • First of all, "Where()" method creates an IQueryable which is going to be translated to SQL, and in both of these two ways, we have the same generated SQL (not exactly the same, there is a slight difference). Second of all, there's definitely only 1 element in the sequence because the condition is based on the primary key.

              – Amir Hossein Ahmadi
              Jan 8 at 13:51













            • @AmirHosseinAhmadi As far as I know, Using any() Linq is generate SQL query with exists and return true or false, so there is no require extra condition as you mention in your question.

              – AGH
              Jan 9 at 5:47



















            What are the differences between your approach and my second approach? (They both return a boolean and do the same thing)

            – Amir Hossein Ahmadi
            Jan 6 at 14:02





            What are the differences between your approach and my second approach? (They both return a boolean and do the same thing)

            – Amir Hossein Ahmadi
            Jan 6 at 14:02













            @AmirHosseinAhmadi Using Where () creates an iterator which adds performance impact, whereas using any () with predicate can perform its task without an iterator. In additional, You will get an exception if your condition will find more than 1 record.

            – AGH
            Jan 8 at 5:31





            @AmirHosseinAhmadi Using Where () creates an iterator which adds performance impact, whereas using any () with predicate can perform its task without an iterator. In additional, You will get an exception if your condition will find more than 1 record.

            – AGH
            Jan 8 at 5:31













            First of all, "Where()" method creates an IQueryable which is going to be translated to SQL, and in both of these two ways, we have the same generated SQL (not exactly the same, there is a slight difference). Second of all, there's definitely only 1 element in the sequence because the condition is based on the primary key.

            – Amir Hossein Ahmadi
            Jan 8 at 13:51







            First of all, "Where()" method creates an IQueryable which is going to be translated to SQL, and in both of these two ways, we have the same generated SQL (not exactly the same, there is a slight difference). Second of all, there's definitely only 1 element in the sequence because the condition is based on the primary key.

            – Amir Hossein Ahmadi
            Jan 8 at 13:51















            @AmirHosseinAhmadi As far as I know, Using any() Linq is generate SQL query with exists and return true or false, so there is no require extra condition as you mention in your question.

            – AGH
            Jan 9 at 5:47







            @AmirHosseinAhmadi As far as I know, Using any() Linq is generate SQL query with exists and return true or false, so there is no require extra condition as you mention in your question.

            – AGH
            Jan 9 at 5:47




















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53407082%2fwhich-way-of-implemeting-conditions-in-entity-framework-has-a-better-performance%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

            How to fix TextFormField cause rebuild widget in Flutter