rspec/rules/S4635/csharp/rule.adoc

47 lines
1.4 KiB
Plaintext

== Why is this an issue?
Looking for a given substring starting from a specified offset can be achieved by such code: ``++str.Substring(startIndex).IndexOf(char1)++``. This works well, but it creates a new ``++string++`` for each call to the ``++Substring++`` method. When this is done in a loop, a lot of ``++strings++`` are created for nothing, which can lead to performance problems if ``++str++`` is large.
To avoid performance problems, ``++string.Substring(startIndex)++`` should not be chained with the following methods:
* ``++IndexOf++``
* ``++IndexOfAny++``
* ``++LastIndexOf++``
* ``++LastIndexOfAny++``
For each of these methods, another method with an additional parameter is available to specify an offset.
Using these methods gives the same result while avoiding the creation of additional ``++String++`` instances.
=== Noncompliant code example
[source,csharp]
----
str.Substring(StartIndex).IndexOf(char1); // Noncompliant; a new string is going to be created by "Substring"
----
=== Compliant solution
[source,csharp]
----
str.IndexOf(char1, startIndex) - startIndex;
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
include::../highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]