Skip to content

Commit 97ec787

Browse files
committed
Reduce first car render latency and add paired fresh-process benchmarks
Extract byte decoding, color conversion and final encoding into named pure numeric kernels, preserving arithmetic, alpha handling and float rounding. On current .NET 6/7/8 targets, optimize the seven measured numeric kernels at their first call rather than waiting for tiered-JIT promotion. Leave the rest of the runtime policy unchanged and retain normal JIT behavior on the older framework targets. No rendering warmup or global runtime setting is used. Defer TextStyle's shared FontResolver through a thread-safe Lazy instance: geometry-only SVGs and inherited font declarations no longer require building the system font catalog. First real text still resolves the same typeface. Skip the CSS importance regex when the value contains no exclamation mark. Add a cold-car benchmark with a fresh hidden child process for every trial, background-STA parse/preview/freeze/full-render phases, parent process-to-ready measurements and cross-thread frozen drawing validation. Pair baseline and candidate processes in alternating AB/BA order. Support repository override when copying harness binaries to the same drive. Check preview, native-size full output and every native bitmap hash after readiness timing completes. Update changelog and performance documentation before this commit. Retain individual paired samples, medians, warmed checks and methodology in raw JSON. Source sampling, blur radii/edge behavior, filter effects and quality are unchanged. Same-host .NET 8, five fresh-process pairs against 06c5cca, binaries on the same drive and OS caches retained: - Full progressive pipeline: 2184.32 -> 1517.85 ms. - Process launch to full readiness: 2295.52 -> 1628.66 ms (about 29% shorter). - Preview readiness within pipeline: 262.07 -> 288.72 ms; no preview-speed claim. - All five previews and full 900x600 outputs match, including all 70 native filter bitmaps. All twelve warmed workloads retain matching image hashes. Record the startup tradeoff explicitly: warmed timings varied. The stored same-drive car check measured load at 1.52 -> 1.08 s and redraw at 1.07 -> 1.21 s. These changes favor first filtered readiness; they do not guarantee a warmed throughput improvement. Allocation/timing and OS-cache limits are documented. Validation: - New startup tests verify lazy font state for geometry-only SVGs and typeface initialization / glyph output for first real text. - Complete native WPF regressions and all 321 selected resvg checks pass (312 image comparisons and nine historical/undefined render-only cases). - All 14 external animation examples advance without warnings. - Existing exact blur/convolution/encoding and shared-input checks pass. - All nine library/example target builds and DocFX pass with zero warnings/errors. - Staged whitespace check passes; downloaded fixtures remain outside the repo.
1 parent 06c5cca commit 97ec787

14 files changed

Lines changed: 647 additions & 63 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ These entries describe the current repository source. They have not been assigne
1010

1111
#### Performance
1212

13+
- **Cold progressive rendering:** extract byte decoding, color conversion and encoding into named kernels and compile seven profiled numeric kernels with first-call optimization on the current .NET 6/7/8 targets. Other code retains normal tiered optimization; older targets retain their usual JIT behavior. Geometry-only SVGs defer the thread-safe font catalog until a typeface is actually requested. CSS values without `!` skip the importance regex.
14+
- Add a fresh-process car benchmark with parse/preview/filter/freeze phases, parent process-to-ready timing, alternating baseline/candidate trial order and full preview/image/native-bitmap hashes. Five paired .NET 8 trials against `06c5cca`: full pipeline 2.18 s → 1.52 s; process launch to full readiness 2.30 s → 1.63 s. Preview readiness was 262 → 289 ms. All previews, native-size complete images and 70 filter bitmaps match exactly.
15+
- Record the startup tradeoff in the performance guide: warmed timings varied, and the recorded warmed redraw was 1.07 s → 1.21 s. Add regression checks that geometry-only rendering leaves the font catalog uninitialized and first real text still resolves/renders its typeface correctly.
16+
1317
- **Further car optimization:** process blur columns through tiled transposition and contiguous row kernels; retain identical sliding-sum order, box radii, edge handling and sampling resolution. Black/white/grayscale inputs skip duplicate channel arithmetic. Large numeric buffers use at most four-way parallelism; WPF objects stay on the calling STA and small buffers stay serial.
1418
- Fuse native pixel decoding with the initial color conversion for sole SourceGraphic Gaussian filters, and let those filters donate their temporary input as scratch. Multi-primitive/shared-input graphs retain immutable inputs. Fuse final sRGB conversion and byte encoding while preserving intermediate float rounding, removing another full float-frame allocation.
1519
- Same-host .NET 8 five-run medians against `dd6ade6`: car load 5.07 s → 1.12 s; redraw 5.16 s → 0.94 s. Caller-thread managed allocation fell from 1.38 GB to 643 MB for load. The 900×600 car output and all 70 native filter bitmaps match exactly, as do all twelve benchmark workloads. Raw results and methodology are recorded in the performance guide; timings are machine/workload specific.

‎Docs/Performance.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,24 @@ A separate fresh-process progressive-loading check published its unfiltered prev
5959

6060
These are elapsed-time medians with a warmup, not a guarantee for every host or cold start. Allocation counters cover the caller thread; worker-thread bookkeeping, native buffers and GPU allocations are excluded. In particular, the allocation columns are not peak-memory measurements. The benchmark runs complete baseline and candidate processes serially without other builds/tests running.
6161

62+
## Cold progressive startup
63+
64+
Cold startup now has a separate fresh-process benchmark. Each child times its first parse, unfiltered preview, freeze and complete filtered render on a background STA. The parent stamps preview/full readiness events before validation and hashing. Baseline and candidate binaries use the same drive and alternate trial order. OS disk/font caches are retained.
65+
66+
Five paired .NET 8 trials against `06c5cca` on this host:
67+
68+
| Metric | Before | After |
69+
| --- | ---: | ---: |
70+
| First full pipeline | 2.18 s | 1.52 s |
71+
| Process launch to full readiness | 2.30 s | 1.63 s |
72+
| Pipeline preview readiness | 262 ms | 289 ms |
73+
74+
The measured gain comes from optimized first-call code for the byte/color kernels and blur kernels on the current .NET 6/7/8 targets. Geometry-only documents also defer the managed font catalog until text requests a typeface; their text-style inheritance stays intact. Ordinary CSS values skip unnecessary importance-pattern matching.
75+
76+
This policy favors first filtered readiness. It bypasses tiered compilation for seven pure numeric methods; the rest of the library uses its normal runtime policy. Warmed measurements varied across runs. The recorded same-drive warmed car load was 1.52 s → 1.08 s, while redraw was 1.07 s → 1.21 s. These results include a warmed redraw tradeoff and do not imply uniformly faster steady-state rendering. Older target frameworks retain their usual JIT behavior.
77+
78+
All five previews and full 900×600 car images match, including all 70 native filter bitmaps. All twelve warmed benchmark workloads also retain matching thumbnail, 900×600 and native-bitmap hashes. The cold trials render frozen drawings across threads; validation runs after the readiness event. [Raw cold/warm checks and per-phase samples](https://github.com/dotnetprojects/SVGImage/blob/master/Tests/PerformanceBenchmarks/results/2026-11-03-cold-start-net8.json).
79+
6280
## Reproduce
6381

6482
```powershell

‎Source/SVGImage/SVG/Filters/RasterFilter.Blur.cs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ private static Frame BlurScratch(Frame current,ref Frame first,ref Frame second)
5252
if(ReferenceEquals(current,first)) return second ?? (second=new Frame(current.Data.Length,current.Linear));
5353
return first ?? (first=new Frame(current.Data.Length,current.Linear));
5454
}
55+
#if NETNEXT
56+
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization)]
57+
#endif
5558
private static void Transpose(Frame input,Frame output,int columns,int rows)
5659
{
5760
const int tile=16;
@@ -77,6 +80,9 @@ private static void BoxBlurRows(Frame input,Frame output,int radius,int length,i
7780
else BlurGrayRow(input.Data,output.Data,line*length*4,length,radius,duplicate,wrap,divisor,channels);
7881
});
7982
}
83+
#if NETNEXT
84+
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization)]
85+
#endif
8086
private static int BlurChannels(float[] data)
8187
{
8288
bool black=true,white=true;
@@ -89,6 +95,9 @@ private static int BlurChannels(float[] data)
8995
}
9096
return black ? 1 : white ? 2 : 3;
9197
}
98+
#if NETNEXT
99+
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization)]
100+
#endif
92101
private static void BlurGrayRow(float[] input,float[] output,int start,int length,int radius,bool duplicate,bool wrap,double divisor,int channels)
93102
{
94103
// Black and white height maps require only alpha; other gray maps
@@ -137,6 +146,9 @@ private static void RunNumericRows(int rows,int pixels,Action<int> action)
137146
for(int row=0;row<rows;row++) action(row);
138147
else Parallel.For(0,rows,NumericWorkers,action);
139148
}
149+
#if NETNEXT
150+
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization)]
151+
#endif
140152
private static void BlurRow(float[] input,float[] output,int start,int length,int radius,bool duplicate,bool wrap,double divisor)
141153
{
142154
double r=0,g=0,b=0,a=0;
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
using System;
2+
3+
namespace SVGImage.SVG.Filters
4+
{
5+
internal sealed partial class RasterFilter
6+
{
7+
// These pure numeric kernels need optimized code on their first image,
8+
// rather than waiting for tiered-JIT promotion. Older targets retain
9+
// their usual JIT behavior; benchmark cold and warm paths together.
10+
#if NETNEXT
11+
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization)]
12+
#endif
13+
private static void DecodePixels(byte[] pixels,float[] output,int start,int end,bool linear)
14+
{
15+
for(int i=start;i<end;i+=4)
16+
{
17+
// Match the old byte -> float -> double conversion order.
18+
double a=pixels[i+3]/255f;
19+
output[i+3]=(float)a;
20+
if(linear && a==0) continue;
21+
float r=pixels[i+2]/255f,g=pixels[i+1]/255f,b=pixels[i]/255f;
22+
if(linear)
23+
{
24+
if(r==g && r==b)
25+
{ r=(float)(a*ConvertColor(r/a,true));g=r;b=r; }
26+
else
27+
{ r=(float)(a*ConvertColor(r/a,true));g=(float)(a*ConvertColor(g/a,true));b=(float)(a*ConvertColor(b/a,true)); }
28+
}
29+
output[i]=r;output[i+1]=g;output[i+2]=b;
30+
}
31+
}
32+
#if NETNEXT
33+
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization)]
34+
#endif
35+
private static void ConvertPixels(float[] input,float[] output,int start,int end,bool linear)
36+
{
37+
for(int i=start;i<end;i+=4)
38+
{
39+
double a=input[i+3]; output[i+3]=(float)a;
40+
if(!(a>0)) continue;
41+
if(input[i]==input[i+1] && input[i]==input[i+2])
42+
{
43+
float gray=(float)(a*ConvertColor(input[i]/a,linear));
44+
output[i]=gray; output[i+1]=gray; output[i+2]=gray;
45+
}
46+
else for(int c=0;c<3;c++) output[i+c]=(float)(a*ConvertColor(input[i+c]/a,linear));
47+
}
48+
}
49+
#if NETNEXT
50+
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization)]
51+
#endif
52+
private static void EncodePixels(float[] input,byte[] bytes,int start,int end,bool linear)
53+
{
54+
for(int i=start;i<end;i+=4)
55+
{
56+
double a=input[i+3];
57+
if(linear && (!(a>0) || input[i]==input[i+1] && input[i]==input[i+2]))
58+
{
59+
byte gray=Byte((float)(a>0 ? a*ConvertColor(input[i]/a,false) : 0));
60+
bytes[i]=gray; bytes[i+1]=gray; bytes[i+2]=gray;
61+
}
62+
else if(linear)
63+
{
64+
// Preserve the old intermediate float rounding exactly,
65+
// without allocating another full RGBA float frame.
66+
bytes[i]=Byte((float)(a>0 ? a*ConvertColor(input[i+2]/a,false) : 0));
67+
bytes[i+1]=Byte((float)(a>0 ? a*ConvertColor(input[i+1]/a,false) : 0));
68+
bytes[i+2]=Byte((float)(a>0 ? a*ConvertColor(input[i]/a,false) : 0));
69+
}
70+
else
71+
{
72+
bytes[i]=Byte(input[i+2]); bytes[i+1]=Byte(input[i+1]); bytes[i+2]=Byte(input[i]);
73+
}
74+
bytes[i+3]=Byte(a);
75+
}
76+
}
77+
}
78+
}

‎Source/SVGImage/SVG/Filters/RasterFilter.cs‎

Lines changed: 3 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -173,25 +173,7 @@ private Frame Rasterize(Drawing drawing, bool linear, Rect area)
173173
var pixels=new byte[result.Data.Length]; bitmap.CopyPixels(pixels,width*4,0);
174174
const int batch=16384;
175175
RunNumericRows((pixels.Length+batch-1)/batch,pixels.Length/4,row =>
176-
{
177-
int end=Math.Min(pixels.Length,(row+1)*batch);
178-
for(int i=row*batch;i<end;i+=4)
179-
{
180-
// Match the old byte -> float -> double conversion order.
181-
double a=pixels[i+3]/255f;
182-
result.Data[i+3]=(float)a;
183-
if(linear && a==0) continue;
184-
float r=pixels[i+2]/255f,g=pixels[i+1]/255f,b=pixels[i]/255f;
185-
if(linear)
186-
{
187-
if(r==g && r==b)
188-
{ r=(float)(a*ConvertColor(r/a,true));g=r;b=r; }
189-
else
190-
{ r=(float)(a*ConvertColor(r/a,true));g=(float)(a*ConvertColor(g/a,true));b=(float)(a*ConvertColor(b/a,true)); }
191-
}
192-
result.Data[i]=r;result.Data[i+1]=g;result.Data[i+2]=b;
193-
}
194-
});
176+
DecodePixels(pixels,result.Data,row*batch,Math.Min(pixels.Length,(row+1)*batch),linear));
195177
return result;
196178
}
197179
private static Frame Alpha(Frame frame)
@@ -230,51 +212,14 @@ private static Frame ConvertFrame(Frame input, bool linear)
230212
var result = new Frame(input.Data.Length, linear) { Area = input.Area };
231213
const int batch=16384;
232214
RunNumericRows((input.Data.Length+batch-1)/batch,input.Data.Length/4,row =>
233-
{
234-
int end=Math.Min(input.Data.Length,(row+1)*batch);
235-
for(int i=row*batch;i<end;i+=4)
236-
{
237-
double a=input.Data[i+3]; result.Data[i+3]=(float)a;
238-
if(!(a>0)) continue;
239-
if(input.Data[i]==input.Data[i+1] && input.Data[i]==input.Data[i+2])
240-
{
241-
float gray=(float)(a*ConvertColor(input.Data[i]/a,linear));
242-
result.Data[i]=gray; result.Data[i+1]=gray; result.Data[i+2]=gray;
243-
}
244-
else for(int c=0;c<3;c++) result.Data[i+c]=(float)(a*ConvertColor(input.Data[i+c]/a,linear));
245-
}
246-
});
215+
ConvertPixels(input.Data,result.Data,row*batch,Math.Min(input.Data.Length,(row+1)*batch),linear));
247216
return result;
248217
}
249218
private static void EncodeFrame(Frame input,byte[] bytes)
250219
{
251220
const int batch=16384;
252221
RunNumericRows((bytes.Length+batch-1)/batch,bytes.Length/4,row =>
253-
{
254-
int end=Math.Min(bytes.Length,(row+1)*batch);
255-
for(int i=row*batch;i<end;i+=4)
256-
{
257-
double a=input.Data[i+3];
258-
if(input.Linear && (!(a>0) || input.Data[i]==input.Data[i+1] && input.Data[i]==input.Data[i+2]))
259-
{
260-
byte gray=Byte((float)(a>0 ? a*ConvertColor(input.Data[i]/a,false) : 0));
261-
bytes[i]=gray; bytes[i+1]=gray; bytes[i+2]=gray;
262-
}
263-
else if(input.Linear)
264-
{
265-
// Preserve the old intermediate float rounding exactly,
266-
// without allocating another full RGBA float frame.
267-
bytes[i]=Byte((float)(a>0 ? a*ConvertColor(input.Data[i+2]/a,false) : 0));
268-
bytes[i+1]=Byte((float)(a>0 ? a*ConvertColor(input.Data[i+1]/a,false) : 0));
269-
bytes[i+2]=Byte((float)(a>0 ? a*ConvertColor(input.Data[i]/a,false) : 0));
270-
}
271-
else
272-
{
273-
bytes[i]=Byte(input.Data[i+2]); bytes[i+1]=Byte(input.Data[i+1]); bytes[i+2]=Byte(input.Data[i]);
274-
}
275-
bytes[i+3]=Byte(a);
276-
}
277-
});
222+
EncodePixels(input.Data,bytes,row*batch,Math.Min(bytes.Length,(row+1)*batch),input.Linear));
278223
}
279224
private static int Channel(string value) => value == "R" ? 0 : value == "G" ? 1 : value == "B" ? 2 : 3;
280225
private float Pixel(Frame frame, int x, int y, int c) => x < 0 || y < 0 || x >= width || y >= height ? 0 : frame.Data[(y * width + x) * 4 + c];

‎Source/SVGImage/SVG/TextStyle.cs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ namespace SVGImage.SVG
1212
using System.Windows.Media;
1313
public sealed class TextStyle
1414
{
15-
private static readonly FontResolver _fontResolver = new FontResolver(0);
15+
// Most SVGs contain only geometry. Build the system font catalog only
16+
// when text actually needs a typeface, retaining one thread-safe resolver.
17+
private static readonly Lazy<FontResolver> _fontResolver = new Lazy<FontResolver>(() => new FontResolver(0));
1618
//This should be configurable in some way.
1719
private static readonly TextStyle _defaults = new TextStyle()
1820
{
@@ -54,7 +56,7 @@ public TextStyle(Shape owner)
5456

5557
public Typeface GetTypeface()
5658
{
57-
var fontFamily = _fontResolver.ResolveFontFamily(FontFamily);
59+
var fontFamily = _fontResolver.Value.ResolveFontFamily(FontFamily);
5860
return new Typeface(fontFamily,
5961
Fontstyle,
6062
Fontweight,

‎Source/SVGImage/SVG/Utils/CssStyleSheet.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ internal Dictionary<string, string> Resolve(XmlNode node)
6363
add = (name, value, specificity, allowImportant) =>
6464
{
6565
name = name.StartsWith("--") ? name : name.ToLowerInvariant();
66-
bool important = allowImportant && Regex.IsMatch(value, @"!\s*important\s*$", RegexOptions.IgnoreCase);
66+
bool important = allowImportant && value.IndexOf('!') >= 0 && Regex.IsMatch(value, @"!\s*important\s*$", RegexOptions.IgnoreCase);
6767
if (important) value = Regex.Replace(value, @"!\s*important\s*$", "", RegexOptions.IgnoreCase).Trim();
6868
if (name == "animation")
6969
{

0 commit comments

Comments
 (0)