Mule
Mule

Reputation:

Performance : encapsulating a string in a struct?

Would there be any perforamce gain in ecapsulating a string in a lightweight reference object vs encapsulating a string in a struct. Would the string variable not utlimately point to the heap anyway , irrespective of whether it is contained within a value type or reference type?

Upvotes: 0

Views: 190

Answers (2)

merkuro
merkuro

Reputation: 6167

Since you tagged this one as .NET the string will most certainly be stored on the heap. However I don't think that there will be a noticeable difference and why should there be? First the object or struct must dereferenced and located and after that the string itself. It could be a plus, if you could do without encapsulating the string from a performance and a memory perspective.

Upvotes: 0

Rutger Nijlunsing
Rutger Nijlunsing

Reputation: 5001

The string is always located on the heap, so it wouldn't help. Putting the reference to the string in the struct can only make it slower, since it needs an extra derefence. But this won't be measurable in practice probably.

If you really wanted a string to be on the stack instead of the heap, you would have to create your own custom strings as a struct containing chars. But that's going to be a lot of pain for no gain and can only be used to represent a fixed sized string since the struct is of a fixed size.

Upvotes: 3

Related Questions