Câu hỏi phỏng vấn C#
Câu hỏi

What is the best practice to have b...

Câu trả lời

Here are some best practices for achieving optimal performance when using Lazy objects in C#:

Use Lazy Judiciously

  • Lazy should only be used for objects that are expensive to create and not always needed. For frequently used or lightweight objects, it's better to create them eagerly.

Prefer Lazy over double-checked locking

  • Lazy provides thread-safe initialization out of the box, avoiding the complexity and potential issues with manual double-checked locking.

Use LazyThreadSafetyMode.ExecutionAndPublication

  • This is the default mode for Lazy and ensures that the value is computed only once and all threads get the same instance. Other modes may lead to unnecessary recomputation.

Avoid capturing mutable state in the factory function

  • The factory function passed to Lazy should be a pure function that doesn't capture any mutable state. Capturing mutable state can lead to race conditions and unexpected behavior.

Use Lazy.Value to access the value

  • Always use Lazy.Value to access the unde...
senior

senior

Gợi ý câu hỏi phỏng vấn

middle

What is difference between constant and readonly ?

expert

What is Multicast Delegate in C#?

expert

Explain what is Weak Reference in C#?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào