forked from Taritsyn/JavaScriptEngineSwitcher
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsExecutionLightBenchmark.cs
More file actions
301 lines (259 loc) · 9.42 KB
/
JsExecutionLightBenchmark.cs
File metadata and controls
301 lines (259 loc) · 9.42 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Order;
using JavaScriptEngineSwitcher.ChakraCore;
using JavaScriptEngineSwitcher.Core;
using JavaScriptEngineSwitcher.Core.Utilities;
using JavaScriptEngineSwitcher.Jint;
using JavaScriptEngineSwitcher.Jurassic;
using JavaScriptEngineSwitcher.Msie;
#if NIL_JS
using JavaScriptEngineSwitcher.NiL;
#endif
using JavaScriptEngineSwitcher.Node;
using JavaScriptEngineSwitcher.V8;
using JavaScriptEngineSwitcher.Vroom;
using JavaScriptEngineSwitcher.Yantra;
namespace JavaScriptEngineSwitcher.Benchmarks
{
[MemoryDiagnoser]
[Orderer(SummaryOrderPolicy.Method, MethodOrderPolicy.Declared)]
public class JsExecutionLightBenchmark
{
/// <summary>
/// Name of the file containing library for transliteration of Russian
/// </summary>
private const string LibraryFileName = "russian-translit.js";
/// <summary>
/// Name of transliterate function
/// </summary>
private const string FunctionName = "transliterate";
/// <summary>
/// Number of transliterated items
/// </summary>
private const int ItemCount = 7;
/// <summary>
/// Code of library for transliteration of Russian
/// </summary>
private static string _libraryCode;
/// <summary>
/// List of transliteration types
/// </summary>
private static string[] _inputTypes;
/// <summary>
/// List of input strings
/// </summary>
private static string[] _inputStrings;
/// <summary>
/// List of target output strings
/// </summary>
private static string[] _targetOutputStrings;
/// <summary>
/// Static constructor
/// </summary>
static JsExecutionLightBenchmark()
{
PopulateTestData();
}
/// <summary>
/// Populates a test data
/// </summary>
public static void PopulateTestData()
{
_libraryCode = Utils.GetResourceAsString(
$"Resources.{LibraryFileName}", typeof(JsExecutionLightBenchmark));
_inputTypes =
[
"basic", "letters-numbers", "gost-16876-71", "gost-7-79-2000", "police", "foreign-passport",
"yandex-friendly-url"
];
_inputStrings =
[
"SOLID — мнемонический акроним, введённый Майклом Фэзерсом для первых пяти принципов, названных " +
"Робертом Мартином в начале 2000-х, которые означали пять основных принципов объектно-ориентированного " +
"программирования и проектирования.",
"Принцип единственной ответственности (The Single Responsibility Principle). " +
"Каждый класс выполняет лишь одну задачу.",
"Принцип открытости/закрытости (The Open Closed Principle). " +
"«программные сущности … должны быть открыты для расширения, но закрыты для модификации.»",
"Принцип подстановки Барбары Лисков (The Liskov Substitution Principle). " +
"«объекты в программе должны быть заменяемыми на экземпляры их подтипов без изменения правильности выполнения программы.»",
"Принцип разделения интерфейса (The Interface Segregation Principle). " +
"«много интерфейсов, специально предназначенных для клиентов, лучше, чем один интерфейс общего назначения.»",
"Принцип инверсии зависимостей (The Dependency Inversion Principle). " +
"«Зависимость на Абстракциях. Нет зависимости на что-то конкретное.»",
"SOLID (объектно-ориентированное программирование)"
];
_targetOutputStrings =
[
"SOLID — mnemonicheskij akronim, vvedjonnyj Majklom Fjezersom dlja pervyh pjati principov, nazvannyh " +
"Robertom Martinom v nachale 2000-h, kotorye oznachali pjat' osnovnyh principov ob#ektno-orientirovannogo " +
"programmirovanija i proektirovanija.",
"Princip edinstvennoj otvetstvennosti (The Single Responsibility Principle). " +
"Ka#dyj klass vypolnjaet li6' odnu zada4u.",
"Princip otkrytosti/zakrytosti (The Open Closed Principle). " +
"«programmnye sushhnosti … dolzhny byt' otkryty dlja rasshirenija, no zakryty dlja modifikacii.»",
"Princip podstanovki Barbary Liskov (The Liskov Substitution Principle). " +
"«ob\"ekty v programme dolzhny byt' zamenyaemymi na e'kzemplyary ix podtipov bez izmeneniya pravil'nosti " +
"vypolneniya programmy.»",
"Printsip razdeleniia interfeisa (The Interface Segregation Principle). " +
"«mnogo interfeisov, spetsialno prednaznachennykh dlia klientov, luchshe, chem odin interfeis obshchego " +
"naznacheniia.»",
"Printcip inversii zavisimostei (The Dependency Inversion Principle). " +
"«Zavisimost na Abstraktciiakh. Net zavisimosti na chto-to konkretnoe.»",
"solid-obektno-orientirovannoe-programmirovanie"
];
}
/// <summary>
/// Transliterates a strings
/// </summary>
/// <param name="createJsEngine">Delegate for create an instance of the JS engine</param>
/// <param name="withPrecompilation">Flag for whether to allow execution of JS code with pre-compilation</param>
private static void TransliterateStrings(Func<IJsEngine> createJsEngine, bool withPrecompilation)
{
// Arrange
string[] outputStrings = new string[ItemCount];
IPrecompiledScript precompiledCode = null;
// Act
using (var jsEngine = createJsEngine())
{
if (withPrecompilation)
{
if (!jsEngine.SupportsScriptPrecompilation)
{
throw new NotSupportedException($"{jsEngine.Name} does not support precompilation.");
}
precompiledCode = jsEngine.Precompile(_libraryCode, LibraryFileName);
jsEngine.Execute(precompiledCode);
}
else
{
jsEngine.Execute(_libraryCode, LibraryFileName);
}
outputStrings[0] = jsEngine.CallFunction<string>(FunctionName, _inputStrings[0], _inputTypes[0]);
}
for (int itemIndex = 1; itemIndex < ItemCount; itemIndex++)
{
using (var jsEngine = createJsEngine())
{
if (withPrecompilation)
{
jsEngine.Execute(precompiledCode);
}
else
{
jsEngine.Execute(_libraryCode, LibraryFileName);
}
outputStrings[itemIndex] = jsEngine.CallFunction<string>(FunctionName, _inputStrings[itemIndex],
_inputTypes[itemIndex]);
}
}
// Assert
for (int itemIndex = 0; itemIndex < ItemCount; itemIndex++)
{
Assert.Equal(_targetOutputStrings[itemIndex], outputStrings[itemIndex]);
}
}
[Benchmark]
[Arguments(false)]
[Arguments(true)]
public void ChakraCore(bool withPrecompilation)
{
Func<IJsEngine> createJsEngine = () => new ChakraCoreJsEngine();
TransliterateStrings(createJsEngine, withPrecompilation);
}
[Benchmark]
[Arguments(false)]
[Arguments(true)]
public void Jint(bool withPrecompilation)
{
Func<IJsEngine> createJsEngine = () => new JintJsEngine();
TransliterateStrings(createJsEngine, withPrecompilation);
}
[Benchmark]
[Arguments(false)]
[Arguments(true)]
public void Jurassic(bool withPrecompilation)
{
Func<IJsEngine> createJsEngine = () => new JurassicJsEngine();
TransliterateStrings(createJsEngine, withPrecompilation);
}
#if NET462
[Benchmark]
public void MsieClassic()
{
Func<IJsEngine> createJsEngine = () => new MsieJsEngine(new MsieSettings
{
EngineMode = JsEngineMode.Classic
});
TransliterateStrings(createJsEngine, false);
}
[Benchmark]
public void MsieChakraActiveScript()
{
Func<IJsEngine> createJsEngine = () => new MsieJsEngine(new MsieSettings
{
EngineMode = JsEngineMode.ChakraActiveScript
});
TransliterateStrings(createJsEngine, false);
}
#endif
[Benchmark]
[Arguments(false)]
[Arguments(true)]
public void MsieChakraIeJsRt(bool withPrecompilation)
{
Func<IJsEngine> createJsEngine = () => new MsieJsEngine(new MsieSettings
{
EngineMode = JsEngineMode.ChakraIeJsRt
});
TransliterateStrings(createJsEngine, withPrecompilation);
}
[Benchmark]
[Arguments(false)]
[Arguments(true)]
public void MsieChakraEdgeJsRt(bool withPrecompilation)
{
Func<IJsEngine> createJsEngine = () => new MsieJsEngine(new MsieSettings
{
EngineMode = JsEngineMode.ChakraEdgeJsRt
});
TransliterateStrings(createJsEngine, withPrecompilation);
}
#if NIL_JS
[Benchmark]
public void NiL()
{
Func<IJsEngine> createJsEngine = () => new NiLJsEngine();
TransliterateStrings(createJsEngine, false);
}
#endif
[Benchmark]
public void Node()
{
Func<IJsEngine> createJsEngine = () => new NodeJsEngine();
TransliterateStrings(createJsEngine, false);
}
[Benchmark]
[Arguments(false)]
[Arguments(true)]
public void V8(bool withPrecompilation)
{
Func<IJsEngine> createJsEngine = () => new V8JsEngine();
TransliterateStrings(createJsEngine, withPrecompilation);
}
[Benchmark]
public void Vroom()
{
Func<IJsEngine> createJsEngine = () => new VroomJsEngine();
TransliterateStrings(createJsEngine, false);
}
[Benchmark]
public void Yantra()
{
Func<IJsEngine> createJsEngine = () => new YantraJsEngine();
TransliterateStrings(createJsEngine, false);
}
}
}