/    Sign up×
Community /Pin to ProfileBookmark

Performance Optimization – Variables VS Accessing Array

I have some an array which is the result of an sql query and I want to loop through all of the item in the array and echo them out as part of my code and in some cases the same field is echoed several times.

What would be faster for me to do in this case 1. assign these to variables like so before I start my loop:-

$itemid = $row[‘item_id’]
$itemname = $row[‘item_name’]

or 2. simply keep accessing them via the array access operator [] as I do currently?

Below is a very simplified example of my code

[code=php]

<?php do{?>

<?php

echo $row[‘item_id’]
echo $row[‘item_name’]

?>

<?php }while($row = mysql_fetch_array($result));?>

[/code]

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJul 24.2011 — If there is no functional reason to assign them to variables, then it would seem to be faster to not do so, since it would be an extra step serving no actual purpose.
Copy linkTweet thisAlerts:
@jimmyoneshotauthorJul 26.2011 — Yep I know what you mean there but what I mean is if the array is being accessed over and over again each time the loop reiterates.

Basically I'm wondering what is faster accessing a value stored in a variable or accessing a value stored in an array?

i.e.:-

echo $array['value'];

VS

echo $value
Copy linkTweet thisAlerts:
@DerokorianJul 26.2011 — They are going to be the same. However why don't you use the following syntax instead so there is no special first time interation:
[code=php]
<?php

while( $row = mysql_fetch_array($result) ) {
echo $row['item_id'];
echo $row['item_name'];
}
?>
[/code]
Copy linkTweet thisAlerts:
@jimmyoneshotauthorJul 26.2011 — Yep it seems that is the best way and it's what I've decided to go with ? Thanks Derokorian

Bit off topic but would yourself or anyone else have any ideas on this which is also slightly (maybe) php related? :-

http://www.webdeveloper.com/forum/showthread.php?t=249295

The javascript forum always seems dead and I intend to use the button I mention in that post inside the while loop we've outlined here.
×

Success!

Help @jimmyoneshot spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.3,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...