Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions src/EPPlus.Fonts.OpenType.Benchmarks/FontCacheBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*************************************************************************************************
Required Notice: Copyright (C) EPPlus Software AB.
This software is licensed under PolyForm Noncommercial License 1.0.0
and may only be used for noncommercial purposes
https://polyformproject.org/licenses/noncommercial/1.0.0/

A commercial license to use this software can be purchased at https://epplussoftware.com
*************************************************************************************************
Date Author Change
*************************************************************************************************
12/03/2026 EPPlus Software AB Benchmarks for the font and kerning caches
*************************************************************************************************/
using BenchmarkDotNet.Attributes;
using EPPlus.Fonts.OpenType.TextShaping;
using OfficeOpenXml.Interfaces.Fonts;
using System;
using System.IO;
using System.Text;

namespace EPPlus.Fonts.OpenType.Benchmarks
{
/// <summary>
/// Benchmarks for the caches that keep memory use bounded: parsed fonts shared between font
/// names that resolve to the same file, and the kerning cache of a shaper.
/// </summary>
[MemoryDiagnoser]
[SimpleJob(warmupCount: 3, iterationCount: 5)]
public class FontCacheBenchmarks
{
private const int UnknownNameCount = 200;
private const string SampleText = "The quick brown fox jumps over the lazy dog. AVAWAY Tolerance.";

private string _fontsPath = string.Empty;
private string _longVariedText = string.Empty;
private OpenTypeFontEngine _engine = null!;
private OpenTypeFont _roboto = null!;
private TextShaper _warmShaper = null!;

[GlobalSetup]
public void Setup()
{
_fontsPath = Path.Combine(AppContext.BaseDirectory, "Fonts");
if (!Directory.Exists(_fontsPath))
throw new DirectoryNotFoundException($"Fonts directory not found: {_fontsPath}");

_engine = CreateEngine();
_roboto = _engine.LoadFont("Roboto", FontSubFamily.Regular);
_warmShaper = new TextShaper(_engine, _roboto);
_warmShaper.Shape(SampleText);

// Latin text with many distinct glyph pairs, more than the kerning cache holds.
var random = new Random(1);
var text = new StringBuilder();
for (int i = 0; i < 200000; i++)
text.Append((char)random.Next(0x21, 0x17F));
_longVariedText = text.ToString();
}

[GlobalCleanup]
public void Cleanup()
{
_engine.Dispose();
}

private OpenTypeFontEngine CreateEngine()
{
return new OpenTypeFontEngine(cfg =>
{
cfg.FontDirectories.Add(_fontsPath);
cfg.SearchSystemDirectories = false;
});
}

/// <summary>
/// A new engine loads 200 font names it cannot find. Every name falls back to the same
/// built-in font, which is parsed once and shared.
/// </summary>
[Benchmark]
public int LoadFont_ManyUnknownNames()
{
using (var engine = CreateEngine())
{
int loaded = 0;
for (int i = 0; i < UnknownNameCount; i++)
{
if (engine.LoadFont("NoSuchFont" + i, FontSubFamily.Regular) != null)
loaded++;
}
return loaded;
}
}

/// <summary>
/// A new shaper shapes 200 000 characters of varied Latin text. The kerning cache fills up
/// and starts over.
/// </summary>
[Benchmark]
public ShapedText Shape_LongVariedText()
{
return new TextShaper(_engine, _roboto).Shape(_longVariedText);
}

/// <summary>
/// A shaper whose kerning cache already holds every pair of the text shapes it again,
/// the common case.
/// </summary>
[Benchmark]
public ShapedText Shape_WarmKerningCache()
{
return _warmShaper.Shape(SampleText);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/*************************************************************************************************
Required Notice: Copyright (C) EPPlus Software AB.
This software is licensed under PolyForm Noncommercial License 1.0.0
and may only be used for noncommercial purposes
https://polyformproject.org/licenses/noncommercial/1.0.0/

A commercial license to use this software can be purchased at https://epplussoftware.com
*************************************************************************************************
Date Author Change
*************************************************************************************************
12/02/2026 EPPlus Software AB Tests for sharing parsed fonts between names
*************************************************************************************************/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OfficeOpenXml.Interfaces.Fonts;
using System;
using System.Collections.Generic;
using System.IO;

namespace EPPlus.Fonts.OpenType.Tests.FontCache
{
/// <summary>
/// Tests that the font store parses a font file once, even when it is requested under many
/// names. Every name the resolver cannot find falls back to the same font, and a spreadsheet
/// can use any number of distinct font names, so without sharing each name would keep its own
/// parsed copy of the same font.
/// </summary>
[TestClass]
public class FontStoreContentSharingTests : FontTestBase
{
public override TestContext? TestContext { get; set; }

/// <summary>
/// Returns a new copy of the bytes registered for a name on every call, like a resolver
/// that reads the font file from disk.
/// </summary>
private class CopyingResolver : IFontResolver
{
private readonly Dictionary<string, byte[]> _fonts = new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);

internal void Add(string fontName, byte[] bytes)
{
_fonts[fontName] = bytes;
}

public byte[] ResolveFont(string fontName, FontSubFamily subFamily)
{
byte[] bytes;
return _fonts.TryGetValue(fontName, out bytes) ? (byte[])bytes.Clone() : null;
}
}

private static byte[] ReadTestFont(string fileName)
{
return File.ReadAllBytes(Path.Combine(FontFolder, fileName));
}

private static OpenTypeFontEngine CreateEngine(IFontResolver resolver)
{
return new OpenTypeFontEngine(cfg => cfg.FontResolver = resolver);
}

private static OpenTypeFontEngine CreateTestFolderEngine()
{
return new OpenTypeFontEngine(cfg =>
{
foreach (var folder in FontFolders)
cfg.FontDirectories.Add(folder);
cfg.SearchSystemDirectories = false;
});
}

[TestMethod]
public void LoadFont_UnknownNamesFallingBackToSameFont_ShareParsedFont()
{
using (var engine = CreateTestFolderEngine())
{
var font1 = engine.LoadFont("NoSuchFont1");
var font2 = engine.LoadFont("NoSuchFont2");

Assert.IsNotNull(font1);
Assert.AreEqual("Archivo Narrow", font1.GetEnglishFontFamilyName());
Assert.AreSame(font1, font2);
}
}

[TestMethod]
public void LoadFont_ResolverReturningFreshCopies_SharesParsedFont()
{
var roboto = ReadTestFont("Roboto-Regular.ttf");
var resolver = new CopyingResolver();
resolver.Add("Name1", roboto);
resolver.Add("Name2", roboto);

using (var engine = CreateEngine(resolver))
{
var font1 = engine.LoadFont("Name1");
var font2 = engine.LoadFont("Name2");

Assert.IsNotNull(font1);
Assert.AreSame(font1, font2);
// A repeated name is still answered from the cache by name.
Assert.AreSame(font1, engine.LoadFont("Name1"));
}
}

[TestMethod]
public void LoadFont_SameLengthDifferentContent_DoesNotShare()
{
var roboto = ReadTestFont("Roboto-Regular.ttf");
// Change the checksum of the first table record. The font still parses, and the two
// files have the same length but different content.
var changed = (byte[])roboto.Clone();
changed[12 + 4] ^= 0xFF;
var resolver = new CopyingResolver();
resolver.Add("Original", roboto);
resolver.Add("Changed", changed);

using (var engine = CreateEngine(resolver))
{
var original = engine.LoadFont("Original");
var other = engine.LoadFont("Changed");

Assert.IsNotNull(original);
Assert.IsNotNull(other);
Assert.AreNotSame(original, other);
}
}

[TestMethod]
public void LoadFont_DifferentFonts_DoNotShare()
{
using (var engine = CreateTestFolderEngine())
{
var roboto = engine.LoadFont("Roboto");
var openSans = engine.LoadFont("Open Sans");

Assert.AreEqual("Roboto", roboto.GetEnglishFontFamilyName());
Assert.AreEqual("Open Sans", openSans.GetEnglishFontFamilyName());
Assert.AreNotSame(roboto, openSans);
}
}

[TestMethod]
public void ClearFontCache_ThenLoad_ParsesAgain()
{
using (var engine = CreateTestFolderEngine())
{
var before = engine.LoadFont("NoSuchFont1");
engine.ClearFontCache();
var after = engine.LoadFont("NoSuchFont2");

Assert.IsNotNull(after);
Assert.AreNotSame(before, after);
}
}
}
}
Loading
Loading