For performance questions similar to this, it is also important to consider the scale, and cost of the operation in question, in this case, DB::prepare()
, among other things.
If the function check()
will only be called once, or a few times per request, page load, etc., would it really matter?
However, if the function check()
will be called several 10s of times (or worse, 100s of times or more), then you should check what does DB::prepare()
cost. You should benchmark. You can do it for a single operation, though in this case, I doubt (no concrete basis :P) it'll yield a 1ms (millisecond) difference. Instead do a worse-case scenario. If you think the function could be called 50 times in some cases, then benchmark on that count.
Honestly? Considering that that function calls a DB operation, network latency and DB server operation would cost you a lot more than that single DB::prepare()
would.
Again, consider the scale and cost, and perform some benchmarks.
Update 2020-12-27 2:21 UTC
In response to @Nick's comment
Forgot to mention the type of performance to consider, eg, CPU, memory, storage, network roundtrip time, etc. The type will dictate the kind of benchmarks you can perform. For now, I'm going to assume CPU usage, specifically, how fast the operation can complete.
Let's say your average number of calls to check()
function is 30 in a request. If it's a range, eg, 20~30, choose the upper limit.
We can start with just the mysqli::prepare()
function in isolation:
$db = new mysqli(...);
$start = microtime(true);
for ($i = 0; $i < 30; $i++) {
$db->prepare('SELECT id FROM table WHERE code = ?');
}
$time = microtime(true) - $start;
var_dump($time); // eg, 0.004544...s = 4.5ms
If we get something like >10ms, or worse >100ms, (arbitrary) then perhaps it might be worth improving.
Next we need to look at the check()
function itself. Calling mysqli::prepare()
30 times might take, say, 30ms, but if calling check()
30 times takes, say, 300ms, then you might want to look at else where first for improvement, eg, using caching instead of always calling DB query.
As for whether keeping mysqli::prepare()
in the function, or out, you need to consider several things other than performance. One is code readability, and in general, code maintainability. I'm sure you've heard the phrase (paraphrasing here) Developer time is more valuable than CPU time.
Also, try to consider other solutions. Say calling mysqli::prepare()
many times does add up, and is worth improving. Instead of moving it out of the function, maybe try keeping it in the function, but still calling it once by, say, storing the result in a static variable, eg:
function check($db, $code) {
static $stmt = null;
if (!$stmt) {
$stmt = $db->prepare(...);
}
$stmt->bind_param(...);
...
}
I'm sure there are better solutions, but in this specific case, I would prefer this than moving the mysqli::prepare()
out of the function.