Should PDO prepared statements be freed up after use? And if so, how? Specifically I'm asking about MySQL - how can you, and should you, call DEALLOCATE PREPARE
though PDO. (Edit: To clarify, this question is not referring to emulated prepares, but real prepares. )
Also - will this free the results set (when large)?
Explanation:
I have seen code along the lines of
$stmnt = $db->prepare($sql);
$stmnt->execute($aParams);
$stmnt = null;
which led me to wondering what this does, when, and if f unset($stmnt);
would be different?
The manual indicates that
When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. [...] By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle.
which tends to suggest you should unallocate the statement, and MySQL has the capability. So,
DEALLOCATE PREPARE
, and howFor completeness, another SO question referring to "free_result" and "close" functions for mysqli_()
suggests that freeing the statement actually adds time (unless you have large memory usage and need the space). But "free_result" is different from freeing the SQL server from having the prepared statment cached.
PDFRSS. Removes the prepared statement with the specified name from the prepared statements in the current workgroup.
PDO::prepare — Prepares a statement for execution and returns a statement object.
In order to use MySQL prepared statement, you use three following statements: PREPARE – prepare a statement for execution. EXECUTE – execute a prepared statement prepared by the PREPARE statement. DEALLOCATE PREPARE – release a prepared statement.
PDO—PHP Data Objects—are a database access layer providing a uniform method of access to multiple databases. It doesn't account for database-specific syntax, but can allow for the process of switching databases and platforms to be fairly painless, simply by switching the connection string in many instances.
Yes. When you are done with the prepare statement you can set it to NULL
or use unset()
.
For a script with multiple queries and large databases, this makes a difference. You can test with:
$before = memory_get_usage();
$stmt = NULL;
die(memory_get_usage() - $before);
For me, this saved 20MB of memory, which was crashing the script later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With