In the String
class there is a method IsInterned()
. I never use this method. Please help me to understand the best uses of this method.
In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned.
The Intern method uses the intern pool to search for a string equal to the value of str . If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to str is added to the intern pool, then that reference is returned.
Consider that interning is an optimisation; it trades a decrease in some desirable qualities for an increase in others. In particular interning has the following good qualities:
It has the following bad qualities:
As an optimisation, we use it where the either the good qualities out-weigh the bad or where the bad qualities don't hold (if we know the string is going to be around for the lifetime of the application anyway, or know it will be used many times, then the bad part doesn't hold).
And by the same token we don't use it where the bad qualities will out-weigh the good. (Most of the time).
IsInterned()
can be used to find a part-way point.
Consider I have a string property Name
:
public string Name { get; set; }
Let's say I know that it's common to look for objects with a given Name
, or to try to find objects with the same Name
or otherwise do a lot of equality comparisons on it. OR Let's say I know there will be a lot of other objects with the same Name
. OR Both.
In these cases I might consider interning:
private string _name;
public string Name
{
get { return _name; }
set { _name = string.Intern(value); }
}
Of course, whether this was a good idea or not depends on the good and bad qualities of interning mentioned above.
In-between using and not using is the possibility:
private string _name;
public string Name
{
get { return _name; }
set { _name = string.IsInterned(value) ?? value; }
}
Here if the string value
is already interned then we the down-sides of interning are already at work and we don't suffer any more, so we take advantage of it. But if value
is not already interned then we just use it as-is.
This is also an optimisation, that optimises for a different case. It only benefits if a reasonable number of the values seen are likely to be interned by some other code (or because they match literals in the assembly), otherwise it just wastes time doing lookups. It's probably less often useful than Intern()
which in turn is less often useful than just using the strings and ignoring interning, but that does show a time when it could be useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With