Search code examples
c#inotifypropertychangedstring-comparison

What is the performance expense of string comparisons for INotifyPropertyChanged?


I was wondering about why MS decided to use strings in the design of INotifyPropertyChanged?

My initial worry was the large expense of doing string comparisons on every change notification, and I was wondering whether to keep my property names short to help with the comparisons.

However, given that strings are immutable in .Net, I wondered whether the runtime is intelligent enough to reuse string instances via some kind of hash table, so comparisons are effectively just a reference compare?

Does anyone know the implementation details, or if not, why MS designed it the way they did?


Solution

  • If it wasn't a string, what would you propose? It can't be a PropertyInfo, since not all types that support this use static typing - for example, a DataTable exposes a custom property model for binding purposes, as no many other types (via any of ICustomTypeDescriptor, TypeDescriptionProvider, or ITypedList).

    Even if it was a PropertyInfo, or even if it was a PropertyDescriptor, you couldn't do a comparison on this: a: it would take a lot of work to obtain the reference lookup, b: you're not even guaranteed (for PropertyDescriptor in particular) to get back the same object every time you look.

    So that means, you'd probably end up comparing the name (a string) anyway.

    By using a string, it is cheap to raise this event, and pretty cheap to compare - a string compare is pretty fast, given that most property names are pretty short, and almost all are less than 30 characters. That will compare alarmingly fast, and it not a bottleneck. In most cases, the "what to do now it has changed" will take a lot more time than this string comparison.

    I don't have the implementation in front of me, but I would hope that the string equality check is basically:

    • same reference? return true
    • different length? return false
    • compare char-by-char; return false at first difference
    • return true

    so it shouldn't even be a problem unless all your property names are a: the same length, and b: a very significant length

    Basically: don't worry about it.