MENU

Blog

Xento is a product based organisation with more than 600 IT Professionals including 350+ PHP Professionals working with a healthy dose of creativity and innovation. We promote an open atmosphere, where team members freely voice new ideas and are involved in all phases of our growth. At Xento, working is not just work; it's fun. Nurturing individual talent, fostering team work and recognition are the key elements of the Xento Culture.

Simple Optimization Techniques

Posted by: Milind Chavan | Category: Continuous Improvement, Newsletter, Oct-2014, PHP Development

Optimization technique is a way through which we can make our system faster and feasible. Its not a burden on any developer, its just a practice which we need to follow at the time of writing code. It makes code:

  • Cleaner
  • Easy to understand
  • Provides performance efficiency on server
  • Efficient for web-server and database server
  • Saves execution time
  • Saves memory consumption, etc.

Optimization is not done by any tool or plugin, it’s an approach of a quality developer to produce lightweight and efficient code. Here are some simple optimization techniques which we can follow in our day-to-day code.

Use single quote ( ‘ ‘ ) instead of double quotes ( “ “ ) for strings.

// Wrong approach
$strMessage = “This happened $intCount times”;

// Right approach
$strMessage = ‘This happened’ . $intCount . ‘ times”;

Why? :-
PHP compiles strings with double quotes. If we write any string in single quote, compiler skips that part and its save our compilation time.

Don’t write count(), size(), strlen() functions in for loop.

// Wrong approach
for( $inti = 0; $inti <= count( $arrstrData ); $inti++ ) {
}

// Right approach
$intCount   = count( $arrstrData ); 
for( $inti = 0; $inti <= $intCount; $inti++ ) {
}

Why? :- In every iteration of the loop, count( $arrstrData ) gets calculated. This is unnecessary as generally, count( $arrstrData ) would never change for the loop.

Don’t copy variables for no reason.

// Wrong approach
$strDescription = strip_tags( $_POST['description'] );
echo $description;

// Right approach
echo strip_tags( $_POST['description'] );

Why? :- Whenever we initialize any variable it consumes memory, as per the example we don’t require to allocate the memory for the variable.

Try to use isset() instead of strlen().

// Wrong approach
if( true == strlen( $strMsg ) > 10 )

// Right approach
if( true == isset( $strMsg[10] )

Why? :- strlen() first counts the size of that string or array and then perform check, instead of that isset() checks the existence of particular index into array or string.

Try to avoid the use of preg_match or regex function.

Why? :- The performance cost of regular expression is higher.

Write maximum possible scenario into IF instead of ELSE.

// Wrong approach
$objEmployee = CEmployees::fetchEmployee();

if( CEmployeeStatusType::TYPE_PREVIOUS == $objEmployee->getStatusTypeId() ) {

} elseif( CEmployeeStatusType::TYPE_CURRENT == $objEmployee->getStatusTypeId() ) { }

// Right approach
$objEmployee = CEmployees::fetchEmployee();

if( CEmployeeStatusType::TYPE_CURRENT == $objEmployee->getStatusTypeId() ) {

} elseif( CEmployeeStatusType::TYPE_PREVIOUS == $objEmployee->getStatusTypeId() ) { }

Why? :- Once if condition is satisfied, else condition wont be checked by the compiler and you could save execution time.

Try to use comma instead of dot in echo

// Wrong approach
echo $str1 . $str2 . $str3;

// Right approach
echo $str1, $str2, $str3;

Why? :- If we use dots, PHP joins the string first and then outputs it. While with commas, it just prints them out one after the other.

Try to avoid set unnecessary values into Session

Why? :- Session are stored on server, and unnecessary data consumes extra space on server which add some load on server.

Try to avoid sql queries in a loop (foreach, for, do-while, while)

// Wrong approach
foreach( $arrobjEmployees as $objEmployee ) {
    $objDepartment = CDepartment::fetchDepartmentById();
}

Why? :- In a loop, sql hits database number of times. Which is costly for performance of database server.

Try to use lazy loading by pagination or by any other method (scroll down etc.)

Why? :- It fasten the speed of execution, and loads page faster to client. Which is really a good way to impress our end user.

Try to avoid multiple for-each loop for same array.

// Wrong approach
foreach( $arrobjEmployees as $objEmployee ) {
        $objEmployee->setDepartmentId(2);
}

foreach( $arrobjEmployees as $objEmployee ) {

       if( true == valObj( $objEmployee, ‘CEmployee’ ) {
            if( false == $objEmployee->insert() ) { }

}

// Right approach
foreach( $arrobjEmployees as $objEmployee ) {
        if( true == valObj( $objEmployee, ‘CEmployee’ ) {
            $objEmployee->setDepartmentId(2);
            if( false == $objEmployee->insert() ) { }

}

Remove unused & unnecessary variables and also check variable existence in parent class

Why? :- Its saves unnecessary memory on server.

Try to avoid complex expressions

// Wrong approach
if( CEmployee::EMPLOYEE_STATUS_TYPE_CURRENT == $objEmployee->getEmployeeStatusTypeId() ||
CEmployee::EMPLOYEE_STATUS_TYPE_NOTICE == $objEmployee->getEmployeeStatusTypeId() ) { }

// Right approach
if( true == in_array( $objEmployee->getEmployeeStatusTypeId(),  array(
CEmployee::EMPLOYEE_STATUS_TYPE_CURRENT, CEmployee::EMPLOYEE_STATUS_TYPE_NOTICE ) ) { }

Combine cases wherever possible

// Wrong approach
public static function isVisaPayment( $intPaymentTypeId ) {

   switch( $intPaymentTypeId ) {

       case self::PAYMENT_TYPE_CASH:
           return false;

       case self::PAYMENT_TYPE_CHECK:
           return false;

       case self::PAYMENT_TYPE_MONEY_ORDER:
           return false;

       case self::PAYMENT_TYPE_CHECK_21:
           return true;

       case self::PAYMENT_TYPE_VISA:
           return false;

       default:
           trigger_error( 'Invalid payment type id.', E_USER_WARNING );
           break;
   }
}

// Right approach
public static function isVisaPayment( $intPaymentTypeId ) {

   switch( $intPaymentTypeId ) {

       case self::PAYMENT_TYPE_CASH:
       case self::PAYMENT_TYPE_CHECK:
       case self::PAYMENT_TYPE_MONEY_ORDER:
       case self::PAYMENT_TYPE_CHECK_21:
          return false;

       case self::PAYMENT_TYPE_VISA:
           return false;

       default:
           trigger_error( 'Invalid payment type id.', E_USER_WARNING );
           break;
   }
}

A Developer should always set TRUE for notice, issue, warning on development environment, so QAs can catch that issue on local. This process can prevent errors from reaching clients.

Milind Chavan