Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the StringSegment class? [closed]

Tags:

c#

In the Microsoft.Extensions.Primitives package lib there is a class StringSegment for which the comments indicate that it is:

An optimized representation of a substring.

I was unaware of this particular class, until I discovered aspnet announcement #244, stating: Microsoft.Net.Http.Headers converted to use StringSegments.

Still, looking at the implementation of the StringSegment class, I fail to see what purpose it actually serves. I see a buffer, which I guess would indicate better manipulation on partial characters (the 'segment' part perhaps?). I also see several helper functions which are closely related - if not identical - in behaviour to those already available at regular strings, such as StartsWith/Endswith, Substring etc. The aspnet-core docs list these in full, but again this also lacks context on "why" it should be used.

So what exactly is the purpose of the StringSegment class and in which scenarios is it applicable to use it?

Is it useful to call the class in my application code, when I manipulate strings? Can we have an example, where it will be beneficial?

like image 712
Juliën Avatar asked May 24 '17 15:05

Juliën


1 Answers

It lets you perform a variety of string operations on a substring of another string, without actually calling Substring() and creating a new string object. It's roughly analogous to the way in C you can have a pointer into the middle of a string.

like image 87
15ee8f99-57ff-4f92-890c-b56153 Avatar answered Sep 30 '22 06:09

15ee8f99-57ff-4f92-890c-b56153