Skip to content

Conversation

BR903
Copy link

@BR903 BR903 commented Apr 30, 2025

When the string to be measured seems likely to be significantly longer than the maximum width, use font metrics to estimate a prefix of the string to measure first. Since harfbuzz has to shape the entire string before any of it can be measured, a good first estimate reduces useless work, and avoids quadratic performance from common use cases.

More details:

Harfbuzz shaping is done over the entire input string before any of it can be measured. In the case of a string that is much longer than the maximum width, most of the produced shaping data is not relevant.

A common use case for TTF_MeasureString() is to identify a line's worth of text from a string, and then call the function again with the remainder of the string, repeating this process until the string is fully consumed. But if the entire string is shaped on each call, this results in quadratic performance.

Absent new functionality in harfbuzz, one solution is for TTF_MeasureString() to use font metrics to quickly estimate a likely prefix that will still meet or exceed the caller's maximum width, and process that prefix instead. (If this prefix proves to be shorter than the maximum width, then the code will retry with longer prefixes until a correct return value is found, but this will almost never happen.)

Since this estimation is potentially redundant work, it is only done for strings that appear likely to be significantly longer than the maximum width. All other strings are processed normally, as before this change.

When the string to be measured seems likely to be significantly longer
than the maximum width, use font metrics to estimate a prefix of the
string to measure first. Since harfbuzz has to shape the entire string
before any of it can be measured, a good first estimate reduces
useless work, and avoids quadratic performance from common use cases.
@sezero sezero requested a review from slouken May 5, 2025 07:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant