Disadvantages of Lazy?

后端 未结 7 1976
青春惊慌失措
青春惊慌失措 2021-01-31 14:37

I recently started using Lazy throughout my application, and I was wondering if there are any obvious negative aspects that I need to take into account when using Lazy<

7条回答
  •  自闭症患者
    2021-01-31 14:51

    I'll expand a bit on my comment, which reads:

    I've just started using Lazy, and find that it's often indicative of bad design; or laziness on the part of the programmer. Also, one disadvantage is that you have to be more vigilant with scoped up variables, and create proper closures.

    For example, I've used Lazy to create the pages the user can see in my (sessionless) MVC app. It's a guiding wizard, so the user might want to go to a random previous step. When the handshake is made, an array of Lazy objects is crated, and if the user specifies as step, that exact page is evaluated. I find it delivers good performance, but there are some aspects to it that I don't like, for example many of my foreach constructs now look like this:

    foreach(var something in somethings){
         var somethingClosure = something;
         list.Add(new Lazy(() => new Page(somethingClosure));
    } 
    

    I.e. you have to deal with the problem of closures very proactively. Otherwise I don't think it's such a bad performance hit to store a lambda and evaluate it when needed.

    On the other hand this might be indicative that the programmer is being a Lazy, in the sense that you'd prefer not thinking through your program now, and instead let the proper logic evaluate when needed, as with example in my case - instead of building that array, I could just figure out just what that specific requested page would be; but I chose to be lazy, and do an all in approach.

    EDIT

    It occurs to me that Lazy also has a few peculiars when working with concurrency. For example there's a ThreadLocal for some scenarios, and several flag configurations for your particular multi-threaded scenario. You can read more on msdn.

提交回复
热议问题