Skip to content

Instantly share code, notes, and snippets.

@gam6itko
Created November 14, 2022 12:12
Show Gist options
  • Save gam6itko/2ee6068fef0b12a1dcb47aa337364cf8 to your computer and use it in GitHub Desktop.
Save gam6itko/2ee6068fef0b12a1dcb47aa337364cf8 to your computer and use it in GitHub Desktop.
php batching sql query build performance
<?php
/**
* If you build SQL queries like INSERT INTO table ('f1', 'f2', ...) VALUES ('v1', 'v2', ...), ('v1', 'v2', ...), ...
* You should know what
*
* Expression
* `rtrim(str_repeat('?,', TRY_COUNT), ',');`
* works 16 time faster than
* `implode(',', array_pad([], TRY_COUNT, '?'));`
*/
declare(strict_types=1);
const TRY_COUNT = 1_000;
const PLACEHOLDERS_COUNT = 1_000;
printf("try on count %d\n", TRY_COUNT * PLACEHOLDERS_COUNT);
$startTime = microtime(true);
for ($i = 0; $i < TRY_COUNT; $i++) {
for ($j = 0; $j < PLACEHOLDERS_COUNT; $j++) {
implode(',', array_pad([], TRY_COUNT, '?'));
}
}
$implodeResult = microtime(true) - $startTime;
printf("implode time: %f\n", $implodeResult);
$startTime = microtime(true);
for ($i = 0; $i < TRY_COUNT; $i++) {
for ($j = 0; $j < PLACEHOLDERS_COUNT; $j++) {
rtrim(str_repeat('?,', TRY_COUNT), ',');
}
}
$strRepeatResult = microtime(true) - $startTime;
printf("str_repeat time: %f\n", $strRepeatResult);
printf('str_repeat faster than implode in %f times', $implodeResult / $strRepeatResult);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment