-
-
Notifications
You must be signed in to change notification settings - Fork 594
Expand file tree
/
Copy pathPreparedScriptBenchmark.cs
More file actions
71 lines (60 loc) · 2.53 KB
/
PreparedScriptBenchmark.cs
File metadata and controls
71 lines (60 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using BenchmarkDotNet.Attributes;
namespace Jint.Benchmark;
/// <summary>
/// Replicates the exact pattern from JavaScriptEngineSwitcher's JsExecutionHeavyBenchmark:
/// a Handlebars template rendering library is loaded on 4 separate engine instances,
/// each calling renderTemplate() with different content items.
/// See: https://github.com/Taritsyn/JavaScriptEngineSwitcher/blob/master/test/JavaScriptEngineSwitcher.Benchmarks/JsExecutionHeavyBenchmark.cs
/// </summary>
[MemoryDiagnoser]
public class PreparedScriptBenchmark
{
private string _libraryCode = null!;
private Prepared<Script> _preparedLibrary;
private ContentItem[] _contentItems = null!;
[GlobalSetup]
public void Setup()
{
var handlebars = File.ReadAllText("Scripts/template-rendering/lib/handlebars.js");
var helpers = File.ReadAllText("Scripts/template-rendering/lib/helpers.js");
_libraryCode = handlebars + "\n" + helpers;
_preparedLibrary = Engine.PrepareScript(_libraryCode);
var contentDir = "Scripts/template-rendering/content";
string[] names = ["hello-world", "contacts", "js-engines", "web-browser-family-tree"];
_contentItems = names.Select(name => new ContentItem(
File.ReadAllText(Path.Combine(contentDir, name, "template.handlebars")),
File.ReadAllText(Path.Combine(contentDir, name, "data.json"))
)).ToArray();
}
[Benchmark(Baseline = true)]
public void ExecuteStringOnMultipleEngines()
{
RenderTemplates(withPrecompilation: false);
}
[Benchmark]
public void ExecutePreparedOnMultipleEngines()
{
RenderTemplates(withPrecompilation: true);
}
private void RenderTemplates(bool withPrecompilation)
{
// First engine: load library and render first item
var engine = new Engine();
if (withPrecompilation)
engine.Execute(_preparedLibrary);
else
engine.Execute(_libraryCode);
engine.Invoke("renderTemplate", _contentItems[0].Template, _contentItems[0].Data);
// Remaining engines: each loads the same library and renders one item
for (int i = 1; i < _contentItems.Length; i++)
{
engine = new Engine();
if (withPrecompilation)
engine.Execute(_preparedLibrary);
else
engine.Execute(_libraryCode);
engine.Invoke("renderTemplate", _contentItems[i].Template, _contentItems[i].Data);
}
}
private sealed record ContentItem(string Template, string Data);
}