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?
If it wasn’t a
string, what would you propose? It can’t be aPropertyInfo, since not all types that support this use static typing – for example, aDataTableexposes a custom property model for binding purposes, as no many other types (via any ofICustomTypeDescriptor,TypeDescriptionProvider, orITypedList).Even if it was a
PropertyInfo, or even if it was aPropertyDescriptor, 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 (forPropertyDescriptorin 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:
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.