[php-src] Issue #15376: str_overwrite() as a faster, in place alternative to substr_replace()

From: Date: Tue, 13 Aug 2024 10:41:40 +0000
Subject: [php-src] Issue #15376: str_overwrite() as a faster, in place alternative to substr_replace()
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-247486@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/15376 Author: nevez ### Description Let's say $a is a large binary string. I want to overwrite multiple small portions of it (think serialized objects in a big file). Currently I have to use a for loop, copying chars one by one, or use substr_replace(). The interpreted for loop on my pc is **5 orders of magnitude** faster, probably because substr_replace() has to allocate and return a new string each time. What I am suggesting is a substr_replace() with the first $string parameter passed by reference, essentially implementing that for loop natively, with memcpy or similar. Should be quick to implement. Test code: ``` <?php $a = str_repeat("\x00", 100000000); $n = 100; $start = microtime(true); for ($i=0;$i<$n;$i++) { $s = rand(0, 24999999) * 4; $e = $s + 4; $b = "abcd"; $c = 0; for ($j = $s, $c = 0; $j < $e; $j++, $c++) { $a[$j] = $b[$c]; } } $end = microtime(true); echo "With for loop: ".($end - $start)."\n"; $start = microtime(true); for ($i=0;$i<$n;$i++) { $a = substr_replace($a, "abcd", rand(0, 24999999) * 4, 4); } $end = microtime(true); echo "With substr_replace(): ".($end - $start)."\n"; // On my PC: With for loop: 4.3869018554688E-5 With substr_replace(): 4.4326999187469 ```

« previous php.bugs (#247486) next »