1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-11-26 14:38:34 +01:00

reduce string allocations when rendering text

This commit is contained in:
Ellpeck 2020-06-21 23:23:52 +02:00
parent 92c91928b2
commit d891e19d2a
3 changed files with 32 additions and 2 deletions

View file

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
namespace MLEM.Extensions {
/// <summary>
/// A set of extensions for dealing with <see cref="char"/>
/// </summary>
public static class CharExtensions {
private static readonly Dictionary<char, string> Cache = new Dictionary<char, string>();
/// <summary>
/// Returns the string representation of this character which will be stored and retrieved from a dictionary cache.
/// This method reduces string allocations, making it trade in processor efficiency for memory efficiency.
/// </summary>
/// <param name="c">The character to turn into a string</param>
/// <returns>A string representing the character</returns>
public static string ToCachedString(this char c) {
if (!Cache.TryGetValue(c, out var ret)) {
ret = c.ToString();
Cache.Add(c, ret);
}
return ret;
}
}
}

View file

@ -1,6 +1,8 @@
using System.Text; using System.Text;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using MLEM.Extensions;
using MLEM.Misc;
namespace MLEM.Font { namespace MLEM.Font {
/// <inheritdoc/> /// <inheritdoc/>
@ -32,7 +34,7 @@ namespace MLEM.Font {
/// <inheritdoc /> /// <inheritdoc />
protected override Vector2 MeasureChar(char c) { protected override Vector2 MeasureChar(char c) {
return this.Font.MeasureString(c.ToString()); return this.Font.MeasureString(c.ToCachedString());
} }
/// <inheritdoc/> /// <inheritdoc/>

View file

@ -3,6 +3,7 @@ using System.Linq;
using System.Text; using System.Text;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using MLEM.Extensions;
using MLEM.Font; using MLEM.Font;
using MLEM.Formatting.Codes; using MLEM.Formatting.Codes;
using MLEM.Misc; using MLEM.Misc;
@ -124,7 +125,7 @@ namespace MLEM.Formatting {
if (i == 0) if (i == 0)
token.DrawSelf(time, batch, pos + innerOffset, font, color, scale, depth); token.DrawSelf(time, batch, pos + innerOffset, font, color, scale, depth);
var cString = c.ToString(); var cString = c.ToCachedString();
token.DrawCharacter(time, batch, c, cString, i, pos + innerOffset, drawFont, drawColor, scale, depth); token.DrawCharacter(time, batch, c, cString, i, pos + innerOffset, drawFont, drawColor, scale, depth);
innerOffset.X += font.MeasureString(cString).X * scale; innerOffset.X += font.MeasureString(cString).X * scale;
} }