Skip to content

Parse integers in a string based on an index #16933

@hughbe

Description

@hughbe

Summary

Currently parsing integers takes a string, and parses the entirety of the string. I propose adding APIs to parse a string from an index, with an additional overload specifying the length.

Rationale

In order to parse part of a string, we need to perform a string.Substring(...) method on the string. This results in allocations, affecting performance.

Proposed APIs - with slices

public int Parse(ReadOnlySlice<char> s)
public int Parse(ReadOnlySlice<char> s, IFormatProvider format);

public bool TryParse(ReadOnlySlice<char> s, out int i);
public bool TryParse(ReadOnlySlice<char> s, IFormatProvider format, out int i);

Proposed APIs - without slices

public class Int32
{
    // Proposed new APIs
    public int Parse(string s, int index);

    // Either
     public int Parse(string s, int index, int count);
     // or
     Public int Parse(string s, int index, int length);
     // or
     public int Parse(string s, int startIndex, int endIndex);

    // Existing parsing APIs
    public int Parse(string);
    ...
}

Discussion

  • These overloads should be intelligent and not allocate any substrings
  • I assume TryParse overloads would also have to be added
  • Would we need to add overloads taking an IFormatProvider too
  • How common is this use case?
  • Is this worth adding 4 public methods to each integer type?
  • Should we bother with the Parse(string, int) overload? I think most people calling his API would know the required length.

Example

I added some custom parsing code in a PR in coreclr (dotnet/coreclr#3992). This is basically the code that these proposed methods would use.
Parsing performance of ints in Version increased by up to 4x due to reduced substring allocations.

Another example is Guid (dotnet/coreclr#3965) where performance of parsing Guid strings increased by up to 3x with the allocation count reducing to 0.

Alternatives

  • Add a Parse(char* s, int count) method instead but this is rare

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions