Why is String.IsNullOrEmpty faster than String.Length?

前端 未结 7 2055
心在旅途
心在旅途 2020-12-14 17:28

ILSpy shows that String.IsNullOrEmpty is implemented in terms of String.Length. But then why is String.IsNullOrEmpty(s) faster than

相关标签:
7条回答
  • 2020-12-14 18:09

    In CLR via CSharp chapter 10 "Properties" Jeff Richter writes:

    A property method can take a long time to execute; field access always completes immediately. A common reason to use properties is to perform thread synchronization, which can stop the thread forever, and therefore, a property should not be used if thread synchronization is required. In that situation, a method is preferred. Also, if your class can be accessed remotely (for example, your class is derived from System.MarshalByRefObject), calling the property method will be very slow, and therefore, a method is preferred to a property. In my opinion, classes derived from MarshalByRefObject should never use properties.

    So if we see String.Length is property and String.IsNullOrEmpty is a method which may execute faster than the property String.Length.

    0 讨论(0)
提交回复
热议问题