Replies: 2 comments 4 replies
-
[Benchmark]
[Arguments("qwertyuiopasdfghjklzxcvbnm")]
public int StringInfoLength(string str) => new StringInfo(str).LengthInTextElements;
[Benchmark]
[Arguments("qwertyuiopasdfghjklzxcvbnm")]
public int LengthFromTextElements(string str)
{
int TextElementCount = 0;
int Index = 0;
while (true)
{
int Length = StringInfo.GetNextTextElementLength(str.AsSpan(Index));
if (Length <= 0)
{
break;
}
TextElementCount++;
Index += Length;
}
return TextElementCount;
}
The overhead of allocation is negligible comparing to the cost of the algorithm. Moreover, your code has an issue that amplifies the allocation much more. |
Beta Was this translation helpful? Give feedback.
-
|
I want not only |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
The
new StringInfo(string).LengthInTextElementsmethod is used to get the number of graphemes in a string. However, you have to allocate aStringInfo, which is not performant for a method that is an alternative tostring.Length.If you don't want to allocate, you have to write a method like this:
Could this method be added to the standard library?
EDIT: See my proposal: #123092
Beta Was this translation helpful? Give feedback.
All reactions