简体   繁体   中英

How to improve the performance of this PHP code?

This is the structure of the php code that I am using

$Objects = $account->api1(); // This returns an object array with each object being O(data1, data2, data3)
$retValue = array();
foreach($Objects as $O)
{
    if($O->data2 == 'something')
    {
        $data4 = $account->api2($O->data2); // returns a value $data4
        // Initialize $tmp;
        $tmp->data1 = $O->data1;
        $tmp->data3 = $O->data3;
        $tmp->data4 = $data4;
        $retValue[] = $tmp;
    }
}

Basically what I need is an object array of the following for which data2 = 'something'

 O(data1,data3,data4)    

Is there a way in which I can simplify this process. Each api call costs money and also involves request across request which makes this process both costly and also slow.Can this be improved anyway ? Even little bit improvement in performance/no of calls would be really helpful.

Important: I'll assume you have some typos in your question and the following equivalences

  • $data2 means $O->data2 Fixed in the question
  • $O->data4 means $data4 Fixed in the question

Calling $account->api2($O->data2) should always return the same value because you always check that $O->data2 is equal to "something" .. So you can call it just once, insteand of each time you have a hit.

<?php

    $Objects = $account->api1(); // This returns an object array with each object being O(data1, data2, data3)
    $retValue = array();

    foreach($Objects as $O)
    {
        if($O->data2 == 'something')
        {

            // Here, you just call api2 the first time (or never, maybe, if you never needed to)
            $data4 = isset($data4) ? $data4 : $account->api2($O->data2);

            // Initialize $tmp;
            $tmp->data1 = $O->data1;
            $tmp->data3 = $O->data3;
            $tmp->data4 = $data4;
            $retValue[] = $tmp;
        }
    }

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM