Skip to content

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

Merged
LamentXU123 merged 2 commits into
php:masterfrom
LamentXU123:opt-st
Sep 12, 2026
Merged

LamentXU123 merged 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!

@devnexen devnexen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think it s correct. nice follow-up for you is applying the same sort of optimisation in mbstring (mb_str_pad)

@LamentXU123

LamentXU123 commented Sep 12, 2026

Copy link
Copy Markdown
Member Author

Yeah here are some benchmark results if anyone is curious (str_pad):

Padding Target length Calls Before After
"ab" 1 KiB 100,000 51.786 ms 7.368 ms
"ab" 1 MiB 150 73.701 ms 3.326 ms
"abcde" 1 MiB 150 35.517 ms 2.966 ms

@LamentXU123
LamentXU123 merged commit 74e3a69 into php:master Sep 12, 2026
18 checks passed
@LamentXU123
LamentXU123 deleted the opt-st branch September 12, 2026 05:28
LamentXU123 added a commit that referenced this pull request Sep 12, 2026
Follow-up #23661. Use the same optimization on mb_str_pad.

Co-authored-by: David CARLIER <devnexen@gmail.com>
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.

3 participants