Skip to content

ext/standard: Optimize str_pad() using doubling copies - #23661

Open
LamentXU123 wants to merge 2 commits into
php:masterfrom
LamentXU123:opt-st
Open

ext/standard: Optimize str_pad() using doubling copies#23661
LamentXU123 wants to merge 2 commits into
php:masterfrom
LamentXU123:opt-st

Conversation

@LamentXU123

@LamentXU123 LamentXU123 commented Sep 11, 2026

Copy link
Copy Markdown
Member

I was reading standard code recently. The implementation of str_pad here is quite old that we make a loop to pad the strings. The loop goes on if the remaining padding length is smaller than padded-string's length. In modern implementations like OpenJDK for example, we use a doubling algo for this: https://github.com/openjdk/jdk/blob/jdk-21%2B35/src/java.base/share/classes/java/lang/String.java#L4682 This is way more faster than the original one. Let's say we want to pad "ab" for 1 MiB. With the original one we need ~52,000 times of memory copying but with this implementation we only need 20 times.

@jorgsowa jorgsowa left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Neat finding!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants