Skip to content

Refactor: Use O(1) dereferencing for string emptiness checks instead of strlen()#613

Merged
jgm merged 1 commit into
commonmark:masterfrom
ismaileneskucuk:optimize-strlen-checks
May 27, 2026
Merged

Refactor: Use O(1) dereferencing for string emptiness checks instead of strlen()#613
jgm merged 1 commit into
commonmark:masterfrom
ismaileneskucuk:optimize-strlen-checks

Conversation

@ismaileneskucuk
Copy link
Copy Markdown
Contributor

Using strlen(str) > 0 to check for empty strings incurs an unnecessary O(N) cost, especially inside node rendering functions where it might be called repeatedly.

Checking the first character str[0] is the idiomatic C approach for an O(1) emptiness check.

This PR updates src/commonmark.c and src/main.c to use this safer and more performant approach, preventing potential performance bottlenecks on large documents with extensive attributes.

@jgm
Copy link
Copy Markdown
Member

jgm commented May 26, 2026

This makes sense to me, thanks. @nwellnhof any objections?

@nwellnhof
Copy link
Copy Markdown
Contributor

Looks good to me. Unrelated, but you have to check errno after calling strtol to detect invalid and out-of-range numbers reliably.

@jgm jgm merged commit f4a3a00 into commonmark:master May 27, 2026
30 checks passed
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.

3 participants