mirror of
https://github.com/Ellpeck/MLEM.git
synced 2024-11-22 12:58:33 +01:00
reduce string allocations when rendering text
This commit is contained in:
parent
92c91928b2
commit
d891e19d2a
3 changed files with 32 additions and 2 deletions
27
MLEM/Extensions/CharExtensions.cs
Normal file
27
MLEM/Extensions/CharExtensions.cs
Normal 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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -1,6 +1,8 @@
|
|||
using System.Text;
|
||||
using Microsoft.Xna.Framework;
|
||||
using Microsoft.Xna.Framework.Graphics;
|
||||
using MLEM.Extensions;
|
||||
using MLEM.Misc;
|
||||
|
||||
namespace MLEM.Font {
|
||||
/// <inheritdoc/>
|
||||
|
@ -32,7 +34,7 @@ namespace MLEM.Font {
|
|||
|
||||
/// <inheritdoc />
|
||||
protected override Vector2 MeasureChar(char c) {
|
||||
return this.Font.MeasureString(c.ToString());
|
||||
return this.Font.MeasureString(c.ToCachedString());
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
|
|
|
@ -3,6 +3,7 @@ using System.Linq;
|
|||
using System.Text;
|
||||
using Microsoft.Xna.Framework;
|
||||
using Microsoft.Xna.Framework.Graphics;
|
||||
using MLEM.Extensions;
|
||||
using MLEM.Font;
|
||||
using MLEM.Formatting.Codes;
|
||||
using MLEM.Misc;
|
||||
|
@ -124,7 +125,7 @@ namespace MLEM.Formatting {
|
|||
if (i == 0)
|
||||
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);
|
||||
innerOffset.X += font.MeasureString(cString).X * scale;
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue