Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - to copy, or not to copy, that is the variable?

I landed up on this link: https://developers.google.com/speed/articles/optimizing-php

And then did a search about variable copies and found this: Copy or don't copy extra variables in PHP?

So I understand the above concepts but to my understanding the below code is actually good practice but sorta goes against the don't copy statement. Its almost like "don't copy" must have a condition. Ive always understood that doing a function call on every loop is more resource intensive than storing (copy).

$total = total();
for($i=0; $i<$total; $i++){
}

Same applies for (best example I could think of using Google's example):

<?php
$description = strip_tags($_POST['description']);
?>
<img src="" alt="<?php echo $description ?>" title="<?php echo $description ?>" data-description="<?php echo $description ?>" />

I find it hard to believe making a variable copy has more of a performance hit then:

<img src="" alt="<?php echo strip_tags($_POST['description']) ?>" title="<?php echo strip_tags($_POST['description']) ?>" data-description="<?php echo strip_tags($_POST['description']) ?>" />

So I guess the "for no reason" is relevant above?

like image 633
vaughan-ilogic Avatar asked Dec 16 '22 03:12

vaughan-ilogic


1 Answers

If copying variables becomes a performance issue, then something is severely wrong with your application and you've got much bigger issues to worry about. In 99.99999% of cases, this will never be your bottle neck. Going out of your way to purposely avoid copying variables is an act of micro-optimization. Focus on writing clean readable code that makes sense instead of worrying about small micro-optimizations like this. The Google article in question has actually received a lot of criticism in the past as it looks as though it was quickly thrown together by somebody who was grabbing random information from other random misinformed articles.

like image 196
Wayne Whitty Avatar answered Dec 21 '22 22:12

Wayne Whitty