It is important to be careful when searching for characters within a substring. Let’s consider the following example:
if (str.SubString(startIndex).IndexOf(char1) == -1) // Noncompliant: a new string is going to be created by "Substring"
{
// ...
}
A new string
object is created with every call to the Substring
method. When chaining it with any of the
following methods, it creates a new object for one-time use only:
What is the potential impact?
Creating a new object consumes significant system resources, especially CPU and memory.
When using Substring
repeatedly, such as in a loop, it can greatly impact the overall performance of the application or program.
To mitigate the creation of new objects while searching for characters within a substring, it is possible to use an overload of the mentioned
methods with a startIndex
parameter:
if (str.IndexOf(char1, startIndex) == -1) // Compliant: no new instance of string is created
{
// ...
}
Using these methods gives the same result while avoiding the creation of additional string
objects.