Which of these 3 PDO codes has the best performance?

0

Purpose:

Select a single line with LIMIT 1

Internal Use:

The selects receive internal parameters only

You do not need PREPARE because there are no external user data

$pdo = new PDO("mysql:host=A.com;dbname=B; charset=utf8", "C", "PW");

exemplo 1:
$con = $pdo->query("SELECT id,titulo FROM cursos WHERE cod=1 LIMIT 1");
foreach($con as $row) {
echo $row['id'].' - '.$row['titulo']; 
}

Example 2:

$con = $pdo->query("SELECT id,titulo FROM cursos WHERE cod=1 LIMIT 1");
$con->execute();
$sel=$con->fetch();
echo $sel['id'].' - '.$sel['titulo']; 

Example 3:

$con = $pdo->query("SELECT id,titulo FROM cursos WHERE cod=1 LIMIT 1")->fetch();
echo $con['id'].' - '.$con['titulo'];

The selected row contains 80 columns (with or without data)

The 3 works OK, but I have questions about which one to use.

If there is another way, shorter or faster.

    
asked by anonymous 07.02.2018 / 03:59

1 answer

5

If the performance is relevant to your application use a compiled static typing language and preferably use the zero cost abstraction philosophy. Type C, C ++, Rust, eventually C #, Kotlin, Java, D, Go, Swift. Do not use a script language. For PHP performance is irrelevant.

The biggest cost there, and with a large margin of difference, probably a few orders of magnitude, is the query to the database, so if you need better performance think of cache strategy or re-design the application, earnings usually come more design than details in the code.

If you still want some performance gain leave the PDO. Almost nobody needs it and it costs a lot more than direct database access.

Having said all that, the third one is simpler, straightforward and even by directly executing less things is probably the fastest (it will not be easy to measure the performance difference). I say probably because only knowing the implementation of the PDO to know, but I only used the word so it does not seem that the simple fact of having a command less already makes everything faster, it can be that the lack of it generates other consequences that slows down , but in this case it is highly unlikely, and if it happens to escape the PDO.

Then something would be better:

$dados = $mysql->query("SELECT id, titulo FROM cursos WHERE cod = 1")->fetch();
echo $dados['id'] . ' - ' . $dados['titulo'];

But depending on where you use it can make gains by doing otherwise. You can not analyze performance without context.

You can improve by doing something totally different from this, but only in the concrete case with a lot of information available you can know what.

And working is different from being right. Not that this is wrong, I can not say without context, but the alert is.

    
07.02.2018 / 11:45