[buddypress-trac] [BuddyPress] #2985: Performance Tune Loops by Removing Functions from Their Declarations

buddypress-trac at lists.automattic.com buddypress-trac at lists.automattic.com
Fri Dec 31 07:04:23 UTC 2010


#2985: Performance Tune Loops by Removing Functions from Their Declarations
-------------------------+-----------------------------
 Reporter:  jeffsayre    |      Owner:
     Type:  enhancement  |     Status:  new
 Priority:  normal       |  Milestone:  Awaiting Review
Component:  Core         |    Version:  1.3
 Keywords:  performance  |
-------------------------+-----------------------------
 This code construct is quite common throughout BuddyPress core:

 {{{
 for ( $i = 0; $i < count($array); $i++ ) {
      //stuff
 }
 }}}

 This is bad form. Why? Because it sacrifices performance just to save a
 line of code.

 Sure, the code may look prettier, but pretty code does not necessarily
 mean better code. We should focus on writing code for machine performance,
 not for humans to appreciate.

 As a general rule, more times than not, it is a bad practice to put
 functions inside loop declarations.

 Why is this an issue? With each iteration of the loop, the count()
 function gets executed. It gets executed again, and again, and again...
 This adds a lot of extra execution time which equals more processor usage,
 which equals more time before execution is complete.

 How many times should the variable be counted? Once is all that's
 required. A single, additional line of code will turn these resource-
 hogging loops into more processor-friendly code blocks.

 The easy, simple solution:

 {{{
 $count = count($array);
 for ( $i = 0; $i < $count; $i++ ) {
      //stuff
 }
 }}}

 Think this is not an important issue? As BuddyPress (v1.2.7) currently has
 65 occurrences of this poor construct, there's more than likely a
 noticeable performance hit. With large, more active sites, the hit will be
 even higher. As a site's data grows with use, this performance issue
 increases as each array grows larger and larger, meaning that there are
 more elements through which to iterate and at each step trigger the count
 function yet again.

 As there are too many places where this occurs throughout the BP code base
 (including the commandeered bbPress code), I'm not going to submit a
 patch. I do not have the time to volunteer. I just wanted to bring this up
 as an easy-to-address performance tuning measure.

-- 
Ticket URL: <http://trac.buddypress.org/ticket/2985>
BuddyPress <http://buddypress.org/>
BuddyPress


More information about the buddypress-trac mailing list