SVG Path Optimization with H and V Commands
This article explores how replacing standard L (LineTo)
commands with specialized H (Horizontal) and V
(Vertical) commands reduces the file size of SVG vector graphics. By
omitting redundant coordinate data, these commands shorten path strings,
accelerate browser parsing, and decrease overall network payload.
The Coordinate Overhead of Standard Lines
In SVG path syntax, the generic line command is represented by
L (absolute) or l (relative). The
L command requires two parameters: an X coordinate and a Y
coordinate.
<!-- Generic line moving from (10, 20) to (50, 20) -->
<path d="M 10 20 L 50 20" />When drawing purely horizontal or vertical lines, one axis remains
unchanged. Specifying both coordinates introduces redundant data into
the d attribute string.
How H and V Commands Eliminate Redundancy
SVG provides dedicated single-axis line commands: *
H / h (Horizontal LineTo):
Draws a horizontal line from the current point to a target X coordinate.
It requires only one parameter (X). * V /
v (Vertical LineTo): Draws a vertical line from
the current point to a target Y coordinate. It requires only one
parameter (Y).
Uppercase letters represent absolute coordinates, while lowercase letters represent relative offsets.
Comparative Example
Consider a simple 40x40 pixel square starting at (10, 10):
Using standard L commands:
<path d="M10 10 L50 10 L50 50 L10 50 Z" />Total path characters: 30
Using optimized H and V
commands:
<path d="M10 10 H50 V50 H10 Z" />Total path characters: 20
In this basic example, using H and V cuts
the path command length by over 33%.
Key Efficiency Gains
- Reduced Character Count: Eliminating an entire coordinate and its separating space saves 2 to 6 bytes per segment, depending on number precision.
- Chained Coordinate Savings: Multiple consecutive
horizontal or vertical steps can be chained under a single command
letter (e.g.,
H 20 40 60), further condensing the data. - Enhanced Compression: Shorter and more uniform path commands create repeated token patterns that improve the compression ratios of Gzip and Brotli.
- Faster DOM Parsing: Browsers have fewer numeric tokens to parse and convert into floating-point numbers when constructing the SVG DOM.
Vector optimizers and SVGO pipelines utilize H and
V conversions as a standard pass to ensure orthogonal
vector graphics—such as UI icons, charts, and technical diagrams—remain
as lightweight as possible.