Disadvantages of Lazy?

后端 未结 7 1848
青春惊慌失措
青春惊慌失措 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 15:11

    In my opinion, you should always have a reason for choosing Lazy. There are several alternatives depending on the use case and there are definitely cases where this structure is appropriate. But don't use it just because it's cool.

    For example I don't get the point in the page selection example in one of the other answers. Using a list of Lazy for selecting a single element can be well done with a list or dictionary of delegates directly without using Lazy or with a simple switch statement.

    So the most obvious alternatives are

    • direct instantiation for cheap data structures or structures that are anyway needed
    • delegates for things that are needed zero to few times in some algorithm
    • some caching structure for items that should free the memory when not being used for some time
    • some kind of "future" structure like Task that already may start initializing asynchronously before actual usage consuming idle CPU time in cases where the probability is quite high that the structure will be required later on

    In contrast to that, Lazy is often suitable when

    • computationally intense data structures
    • are needed zero to many times in some algorithm where the zero case has a significant probability
    • and the data is local to some method or class and can be garbage collected when not in use any more or the data should be kept in memory for the whole program's runtime

提交回复
热议问题