Skip to content

Commit 7b5818d

Browse files
committed
Benchmark LightnCandy
1 parent e02cbf1 commit 7b5818d

4 files changed

Lines changed: 333 additions & 13 deletions

File tree

‎composer.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
],
2020
"require": {
2121
"php": ">=8.2",
22-
"devtheorem/php-handlebars-parser": "^1.1.0"
22+
"devtheorem/php-handlebars-parser": "^1.1.0",
23+
"zordius/lightncandy": "^1.2"
2324
},
2425
"require-dev": {
2526
"friendsofphp/php-cs-fixer": "^3.94",

‎composer.lock‎

Lines changed: 57 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎tests/lncbenchmark.php‎

Lines changed: 263 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,263 @@
1+
<?php
2+
3+
/**
4+
* LightnCandy benchmark script. Default iterations: 1000.
5+
*
6+
* Usage: php -d opcache.enable_cli=1 -d opcache.jit=tracing tests/lncbenchmark.php
7+
*/
8+
9+
use LightnCandy\LightnCandy;
10+
11+
require __DIR__ . '/../vendor/autoload.php';
12+
13+
$iterations = (int) ($argv[1] ?? 1000);
14+
15+
// A large, complex template exercising as many syntax features as possible.
16+
$template = loadTemplate('large-page');
17+
$partialNames = ['alert', 'breadcrumbs', 'footer-col', 'nav-item', 'page-header', 'pagination', 'side-panel'];
18+
$partialTemplates = [];
19+
20+
foreach ($partialNames as $name) {
21+
$partialTemplates[$name] = loadTemplate($name);
22+
}
23+
24+
$helpers = [
25+
't' => function (string $key, $options) {
26+
$translations = [
27+
'nav.profile' => 'Profile',
28+
'nav.settings' => 'Settings',
29+
'nav.admin' => 'Admin',
30+
'nav.logout' => 'Log Out',
31+
'nav.login' => 'Log In',
32+
'table.actions' => 'Actions',
33+
'table.empty' => 'No records found.',
34+
'pagination.label' => 'Page navigation',
35+
'pagination.prev' => 'Previous',
36+
'pagination.next' => 'Next',
37+
'pagination.showing' => 'Showing {start}–{end} of {total}',
38+
'edit' => 'Edit',
39+
'delete' => 'Delete',
40+
'confirm_delete' => 'Are you sure you want to delete this?',
41+
];
42+
$str = $translations[$key] ?? $key;
43+
foreach ($options['hash'] as $k => $v) {
44+
// for pagination.showing
45+
$str = str_replace('{' . $k . '}', (string) $v, $str);
46+
}
47+
return $str;
48+
},
49+
'formatDate' => function (mixed $value, string $format) {
50+
return date($format, strtotime($value));
51+
},
52+
'formatCurrency' => function (mixed $value, ?string $format) {
53+
return ($format ? "$format " : '') . number_format($value, 2);
54+
},
55+
'replace' => function (string $subject, string $search, ?string $replace) {
56+
return str_replace($search, $replace ?? '', $subject);
57+
},
58+
'eq' => function (mixed $a, mixed $b) {
59+
if ($a === null || $b === null) {
60+
// in JS, null is not equal to blank string or false or zero
61+
return $a === $b;
62+
}
63+
64+
return $a == $b;
65+
},
66+
'and' => function (mixed $a, mixed $b) { return $a && $b; },
67+
'not' => function (mixed $a) { return !$a; },
68+
'gt' => function (mixed $a, mixed $b) { return $a > $b; },
69+
];
70+
71+
$data = [
72+
'lang' => 'en',
73+
'pageTitle' => 'Dashboard',
74+
'siteName' => 'MyApp',
75+
'stylesheets' => [
76+
['url' => '/css/app.css'],
77+
['url' => '/css/print.css', 'media' => 'print'],
78+
],
79+
'bodyClass' => 'page-dashboard',
80+
'sticky' => true,
81+
'rootUrl' => '/',
82+
'logoHtml' => '<img src="/logo.svg" alt="">',
83+
'user' => [
84+
'id' => 1,
85+
'name' => 'Alice',
86+
'avatar' => '/avatars/alice.jpg',
87+
'isAdmin' => true,
88+
'verified' => true,
89+
],
90+
'navItems' => [
91+
['label' => 'Home', 'url' => '/', 'active' => true],
92+
['label' => 'Reports', 'url' => '/reports', 'badge' => '3'],
93+
['label' => 'More', 'url' => '#', 'icon' => 'chevron', 'children' => [
94+
['label' => 'Sub A', 'url' => '/a'],
95+
['label' => 'Sub B', 'url' => '/b'],
96+
]],
97+
],
98+
'alerts' => [
99+
['type' => 'success', 'message' => 'Saved!', 'dismissible' => true, 'icon' => 'check'],
100+
],
101+
'breadcrumbs' => [
102+
['label' => 'Home', 'url' => '/'],
103+
['label' => 'Orders', 'url' => '/orders'],
104+
['label' => 'List', 'url' => '/orders/list'],
105+
],
106+
'heading' => 'Orders',
107+
'headingBadge' => ['type' => 'primary', 'text' => 'Live'],
108+
'subheading' => 'All orders',
109+
'actions' => [
110+
['label' => 'New', 'url' => '/orders/new', 'primary' => true, 'icon' => 'plus'],
111+
],
112+
'hoverable' => true,
113+
'bordered' => false,
114+
'sortBaseUrl' => '/orders',
115+
'currentSort' => ['key' => 'date', 'dir' => 'asc'],
116+
'showActions' => true,
117+
'selectedIndex' => 2,
118+
'columnCount' => 5,
119+
'currency' => 'USD',
120+
'columns' => [
121+
['key' => 'id', 'label' => '#', 'sortable' => true, 'type' => 'text'],
122+
['key' => 'name', 'label' => 'Customer', 'type' => 'link', 'linkTemplate' => '/c/{id}'],
123+
['key' => 'created', 'label' => 'Date', 'sortable' => true, 'type' => 'date', 'format' => 'M j, Y'],
124+
['key' => 'total', 'label' => 'Total', 'type' => 'currency', 'showTotal' => true],
125+
['key' => 'active', 'label' => 'Active', 'type' => 'boolean'],
126+
],
127+
'items' => array_map(fn($i) => [
128+
'id' => (string) $i,
129+
'name' => "Customer $i",
130+
'created' => date('Y-m-d', mktime(0, 0, 0, (int) ceil($i / 28), (($i - 1) % 28) + 1, 2024) ?: null),
131+
'total' => 100.0 * $i,
132+
'active' => (bool) ($i % 2),
133+
'deleted' => false,
134+
'currency' => 'USD',
135+
], range(1, 100)),
136+
'rowActions' => [
137+
['icon' => 'edit', 'style' => 'secondary', 'labelKey' => 'edit', 'urlTemplate' => '/orders/{id}/edit', 'requiresAdmin' => false],
138+
['icon' => 'trash', 'style' => 'danger', 'labelKey' => 'delete', 'urlTemplate' => '/orders/{id}', 'confirm' => true, 'confirmKey' => 'confirm_delete', 'requiresAdmin' => true],
139+
],
140+
'showTotals' => true,
141+
'totals' => ['total' => 5500.00],
142+
'pagination' => [
143+
'hasPrev' => false,
144+
'hasNext' => true,
145+
'prevUrl' => '#',
146+
'nextUrl' => '/orders?page=2',
147+
'start' => 1,
148+
'end' => 10,
149+
'total' => 42,
150+
'pages' => [
151+
['active' => true, 'number' => 1, 'url' => '/orders'],
152+
['active' => false, 'number' => 2, 'url' => '/orders?page=2'],
153+
['ellipsis' => true, 'number' => null, 'url' => ''],
154+
['active' => false, 'number' => 5, 'url' => '/orders?page=5'],
155+
],
156+
],
157+
'sidePanels' => [
158+
[
159+
'id' => 'summary',
160+
'title' => 'Summary',
161+
'type' => 'stats',
162+
'collapsible' => true,
163+
'collapsed' => false,
164+
'stats' => [
165+
['label' => 'Total Orders', 'value' => 42, 'trend' => 'up', 'delta' => 5],
166+
['label' => 'Revenue', 'value' => '$5,500', 'unit' => 'USD', 'delta' => 0],
167+
],
168+
],
169+
],
170+
'footerColumns' => [
171+
['heading' => 'Product', 'links' => [
172+
['label' => 'Features', 'url' => '/features'],
173+
['label' => 'Pricing', 'url' => '/pricing'],
174+
]],
175+
['heading' => 'Legal', 'links' => [
176+
['label' => 'Privacy', 'url' => '/privacy'],
177+
['label' => 'Terms', 'url' => '/terms'],
178+
]],
179+
],
180+
'copyright' => '©',
181+
'showYear' => true,
182+
'currentYear' => 2024,
183+
'social' => [
184+
['name' => 'GitHub', 'url' => 'https://github.com/myapp', 'icon' => 'github'],
185+
],
186+
'scripts' => [
187+
['url' => '/js/vendor.js'],
188+
['url' => '/js/app.js', 'defer' => true],
189+
],
190+
];
191+
192+
$options = [
193+
'flags' => LightnCandy::FLAG_HANDLEBARSJS,
194+
'helpers' => $helpers,
195+
'partials' => $partialTemplates,
196+
];
197+
198+
// Warm up: give the JIT a chance to compile hot paths before we measure.
199+
for ($i = 0; $i < 50; $i++) {
200+
LightnCandy::compile($template, $options);
201+
}
202+
203+
$start = hrtime(true);
204+
205+
for ($i = 0; $i < $iterations; $i++) {
206+
LightnCandy::compile($template, $options);
207+
}
208+
209+
$elapsed = (hrtime(true) - $start) / 1e9;
210+
$perParse = $elapsed / $iterations * 1000;
211+
$code = LightnCandy::compile($template, $options);
212+
$codeBytes = strlen($code === false ? '' : $code);
213+
214+
foreach ($partialTemplates as $src) {
215+
$partialCode = LightnCandy::compile($src, $options);
216+
$codeBytes += strlen($partialCode === false ? '' : $partialCode);
217+
}
218+
219+
printf(
220+
"Compiled %d times in %.3f s | %.3f ms/compile | %.1f KB code (%d partials)\n",
221+
$iterations,
222+
$elapsed,
223+
$perParse,
224+
$codeBytes / 1024,
225+
count($partialTemplates),
226+
);
227+
228+
$renderer = LightnCandy::prepare($code === false ? '' : $code);
229+
230+
// Warm up
231+
for ($i = 0; $i < 50; $i++) {
232+
$renderer($data);
233+
}
234+
235+
$start = hrtime(true);
236+
237+
for ($i = 0; $i < $iterations; $i++) {
238+
$renderer($data);
239+
}
240+
241+
$elapsed = (hrtime(true) - $start) / 1e9;
242+
$perRun = $elapsed / $iterations * 1000;
243+
$outputBytes = strlen($renderer($data));
244+
245+
printf(
246+
"Executed %d times in %.3f s | %.3f ms/render | %.1f KB output\n",
247+
$iterations,
248+
$elapsed,
249+
$perRun,
250+
$outputBytes / 1024,
251+
);
252+
253+
function loadTemplate(string $name): string
254+
{
255+
$filename = __DIR__ . "/templates/$name.hbs";
256+
$template = file_get_contents($filename);
257+
258+
if ($template === false) {
259+
exit("Failed to open $filename");
260+
}
261+
262+
return $template;
263+
}

‎tests/templates/large-page.hbs‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -78,28 +78,28 @@
7878
</tr>
7979
</thead>
8080
<tbody>
81-
{{#each items as |item i|}}
82-
<tr class="{{#if item.deleted}}deleted{{/if}} {{#if (eq @index ../selectedIndex)}}selected{{/if}}" data-id="{{item.id}}">
81+
{{#each items}}
82+
<tr class="{{#if deleted}}deleted{{/if}} {{#if (eq @index ../selectedIndex)}}selected{{/if}}" data-id="{{id}}">
8383
{{#each ../columns}}
84-
<td class="col-{{key}}{{#if item.highlighted}} highlighted{{/if}}">
84+
<td class="col-{{key}}{{#if ../highlighted}} highlighted{{/if}}">
8585
{{#if (eq type "boolean")}}
86-
{{#if (lookup item key)}}<i class="icon-check text-success"></i>{{else}}<i class="icon-times text-muted"></i>{{/if}}
86+
{{#if (lookup ../ key)}}<i class="icon-check text-success"></i>{{else}}<i class="icon-times text-muted"></i>{{/if}}
8787
{{else if (eq type "date")}}
88-
<time datetime="{{formatDate (lookup item key) "Y-m-d"}}">{{formatDate (lookup item key) format}}</time>
88+
<time datetime="{{formatDate (lookup ../ key) "Y-m-d"}}">{{formatDate (lookup ../ key) format}}</time>
8989
{{else if (eq type "currency")}}
90-
{{formatCurrency (lookup item key) ../currency}}
90+
{{formatCurrency (lookup ../ key) ../../currency}}
9191
{{else if (eq type "link")}}
92-
<a href="{{replace linkTemplate "{id}" item.id}}">{{lookup item key}}</a>
92+
<a href="{{replace linkTemplate "{id}" ../id}}">{{lookup ../ key}}</a>
9393
{{else}}
94-
{{lookup item key}}
95-
{{!--- avoid extra whitespace ---}}{{/if}}
94+
{{lookup ../ key}}
95+
{{/if}}
9696
</td>
9797
{{/each}}
9898
{{#if ../showActions}}
9999
<td class="actions">
100100
{{#each ../rowActions}}
101-
{{#unless (and requiresAdmin (not item.isAdmin))}}
102-
<a href="{{replace urlTemplate "{id}" item.id}}"
101+
{{#unless (and requiresAdmin (not ../isAdmin))}}
102+
<a href="{{replace urlTemplate "{id}" ../id}}"
103103
class="btn btn-sm btn-{{style}}"
104104
{{#if confirm}}data-confirm="{{t confirmKey}}"{{/if}}
105105
title="{{t labelKey}}">

0 commit comments

Comments
 (0)