fix Duplicate DrawString#604
Conversation
Co-authored-by: Ethan Lee <flibitijibibo@gmail.com>
| int Length { get; } | ||
| char this[int index] { get; } | ||
| } | ||
| internal struct StringView : IReadOnlyCharList |
There was a problem hiding this comment.
Making this a struct is pointless since you're going to box it anyway, it would be better as a sealed class to read how it's going to behave
There was a problem hiding this comment.
Thank you, I follow your suggestion that use generic method instead of interface argument. So no boxing now.
| #region Internal MeasureString Method | ||
|
|
||
| public Vector2 MeasureString(string text) | ||
| internal Vector2 MeasureString(ref IReadOnlyCharList text) |
There was a problem hiding this comment.
ref just adds overhead here because the argument is of a boxed type (an interface). If you had MeasureString<T>(ref T text) where T : IReadOnlyCharList then ref would make sense and you could avoid boxing.
There was a problem hiding this comment.
Thank you, I have not get the knowledge before. I know it now from https://giannisakritidis.com/blog/Avoid-Struct-Boxing/
| SpriteFont.IReadOnlyCharList view = new SpriteFont.StringBuilderView(text); | ||
| DrawString(spriteFont, ref view, position, color, rotation, origin, scale, effects, layerDepth); |
There was a problem hiding this comment.
As mentioned in another comment, by construction this boxes the StringBuilderView to store it in a reference-typed (IReadOnlyCharList) local, then passes a reference to the reference, which is unnecessary. Either make DrawString generic so you can pass structs into it by-ref or drop the ref here.
There was a problem hiding this comment.
Thank you, I follow your suggestion that use generic method instead of interface argument. So no boxing now.
|
Thanks for doing this refactoring. Have you tested it using VS's memory profiler to see whether it allocates? It's possible the modern .NET JIT is smart enough to optimize out some of the boxing here but I would expect it to box each adapter instance. |
I find that there is box instruction in dotnet IL. So I think it must be fix regardless of whether the JIT can optimize it. |
|
I can't easily test this locally because I don't have any spritefont-based games lying around but the new code looks good. |
Try to unify string class and StringBuilder class.
Core code: