Skip to content

Instantly share code, notes, and snippets.

@timhunt
Created August 5, 2019 15:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timhunt/e5fa1174e920ff266db07e8fcfd4cef8 to your computer and use it in GitHub Desktop.
Save timhunt/e5fa1174e920ff266db07e8fcfd4cef8 to your computer and use it in GitHub Desktop.
Script to explore the memory usage of Moodle's database driver
<?php
require_once(__DIR__ . '/config.php');
raise_memory_limit(MEMORY_HUGE);
$method = 'get_records'; // One of the cases from the switch below.
$numrows = 512 * 1024;
$generatorquery = "
SELECT i AS id, 'A thirty-two char string' || lpad('' || i, 8) AS name
FROM generate_series(1, $numrows) i";
switch ($method) {
case 'none':
$data = [];
break;
case 'array_fill_object':
$data = [];
for ($i = 0; $i < $numrows; $i++) {
$data[] = (object) ['id' => "$i", 'name' => 'A thirty-two char string' . str_pad($i, 8, STR_PAD_LEFT)];
}
break;
case 'array_fill_object_other':
$data = [];
for ($i = 0; $i < $numrows; $i++) {
$row = new stdClass();
$row->id = "$i";
$row->name = sprintf('A thirty-two char string% 8d', $i);
$data[] = $row;
}
break;
case 'get_records':
$data = $DB->get_records_sql($generatorquery);
break;
case 'get_recordset':
$rs = $DB->get_recordset_sql($generatorquery);
$data = [];
foreach($rs as $row) {
$data[] = $row;
}
$rs->close();
break;
}
//var_dump($data);
$PAGE->set_context(context_system::instance());
$PAGE->set_url('/dbmemtest.php');
$PAGE->set_title('DB memory usage test');
echo $OUTPUT->header();
echo $OUTPUT->heading($method);
echo count($data);
echo $OUTPUT->footer();
// method RAM (MB) RAM peak (MB)
// none 39 40.2
// array_fill_object 321 322.1
// array_fill_object_other 449 450.1
// get_records 369 554
// get_recordset 352.8 354
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment