Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to get first character of a string?

Tags:

string

c#

In my class library, a lot of strings will be checked for its first character whether they match a specific character or not. I do this by accessing the first character via index:

var isMatch = stringToCheck[0] == SPECIAL_CHARACTER;

Is there a faster way to do this check?

Background: My class library provides an interface based on strings. They will be converted to an internal data structure for which the above check is necessary. Unfortunately a lot of data is going through the interface. I profiled my test suite resulting in over 40% of the overall time is spend with the single line about.

like image 648
John Threepwood Avatar asked Dec 01 '25 14:12

John Threepwood


1 Answers

No. There is not as far as I can tell.

The fastest way would be the m_firstChar the string class holds, but that is declared private unfortunately.

The this accessor is the fastest way. It points directly to the unmanaged implementation on the CLR, so it is hard to get it faster.

like image 185
Patrick Hofman Avatar answered Dec 04 '25 05:12

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!