Skip to content

Proposal: String.Contains(char) #24068

@danmoseley

Description

@danmoseley

Rationale and Usage

Finding a character in a string is a fairly common primitive operation. Unfortunately we lead users to the pit of failure because mystring.Contains(char) will bind to the Linq version, which can easily be 20x slower than mystring.IndexOf(char) != -1. By adding these to string, the next recompile will give a performance improvement.

Proposed API

    public sealed partial class String : System.Collections.Generic.IEnumerable<char>, System.Collections.IEnumerable, System.IComparable, System.IComparable<string>, System.IConvertible, System.IEquatable<string>, System.ICloneable
    {
        public bool Contains(char value) { throw null; }
        public bool Contains(char value, StringComparison comparisonType) { throw null; }
        public bool Contains(string value) { throw null; }  // already exists 
        public bool Contains(string value, StringComparison comparisonType) { throw null; } // already exists
        public int IndexOf(char value, StringComparison comparisonType) { throw null; } // to implement above
    }

the implementations will simply be

public bool Contains(char value)
{
    return IndexOf(value) != -1;
}

public bool Contains(char value, StringComparison comparisonType)
{
    return IndexOf(value, comparisonType) != -1;
}

Microbenchmark

Searching in 10 and 1000 character strings:

    Method |       Mean |     Error |    StdDev |
---------- |-----------:|----------:|----------:|
 LinqShort | 142.750 ns | 0.4997 ns | 0.4430 ns |
  LinqLong | 180.121 ns | 0.4741 ns | 0.3428 ns |
 FastShort |   7.575 ns | 0.0196 ns | 0.0174 ns |
  FastLong |   8.508 ns | 0.0403 ns | 0.0377 ns |

Variations

The StringComparison overload is in order to search case insensitively if desired. The IndexOf overload is needed to implement it. These could be discarded as the 90% case I would expect to not take a comparison.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions