鍍金池/ 問答/PHP/ 關(guān)于yield使用的不解之處?

關(guān)于yield使用的不解之處?

場景是有四萬條數(shù)據(jù),需要更新某一個字段值,然后使用了yield,感覺使用和不使用的作用不大啊,是不是我用錯了方法?

第一種寫法:

init_data()里獲取數(shù)據(jù)庫數(shù)據(jù),init()方法循環(huán)調(diào)用:

/**
 * 這個方法用來獲取數(shù)據(jù)庫數(shù)據(jù)
 * 每次取2000條數(shù)據(jù)出來 存放在yield
 * 第一次默認取2000 之后會根據(jù)最大ID取2000條數(shù)據(jù)出來
 */
public function init_data()
{
    $search = array(
        'limit' => array(
            'persize' => 1000
        )
    );
    $max_id = 0;
    while(true) {
        if ($max_id === 0) {
            $result = $this->consum_record_model->get_values('id', 'consume_time', null, $search);
        } else if($max_id && $max_id > 0) {
            $attr = array('id_big' => $max_id);
            $result = $this->consum_record_model->get_values('id', 'consume_time', $attr, $search);
        } else {
            break;
        }
        // 對數(shù)組key值(id)排序 取出最大ID 
        krsort($result);
        $max_id = key($result);

        if (empty($result) && !is_array($result)) {
            break;
        } else {
            yield $result;
        }
    }
}

/**
 * 這里利用事務(wù)來對數(shù)據(jù)進行更新操作
 */
public function init($id)
{
    p(memory_get_usage());
    foreach ($this->init_data() as $value) {
        $this->db->trans_begin();
        foreach ($value as $id => $time) {
            $this->db->query("UPDATE consum_record SET time_type = ? WHERE id = ? ", array($this->get_time_type($time), $id));
        }
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }
    }
    p(memory_get_usage());
    exit;
}

第二種寫法:

這種寫法直接在while里面對數(shù)據(jù)庫進行更新操作,只貼init_data()方法的while部分:

while(true) {
    if ($max_id === 0) {
        $result = $this->consum_record_model->get_values('id', 'consume_time', null, $search);
    } else if($max_id && $max_id > 0) {
        $attr = array('id_big' => $max_id);
        $result = $this->consum_record_model->get_values('id', 'consume_time', $attr, $search);
    } else {
        break;
    }
    // 對數(shù)組key值(id)排序 取出最大ID 
    krsort($result);
    $max_id = key($result);

    if (empty($result) && !is_array($result)) {
        break;
    } else {
        $this->db->trans_begin();
        foreach ($result as $id => $time) {
            $this->db->query("UPDATE consum_record SET time_type = ? WHERE id = ? ", array($this->get_time_type($time), $id));
        }
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }
        yield $result;
    }
}

然后我用memory_get_usage()函數(shù)來查看內(nèi)存使用量,兩種方法消耗的內(nèi)存總量相差不多,開始是3M,結(jié)束時都在14M左右,平均執(zhí)行時長在75s上下

看了很多關(guān)于yield的概述,但是實際上對這個特性的應(yīng)用場景并不是很理解,寫的代碼有問題,還請多多指教。

回答
編輯回答
逗婦乳

yield, 是可以在循環(huán)的時候, 代碼內(nèi)外溝通, 能性能貌似沒什么影響.
尤其是這個并不是多線程.
每次的mysql update都是阻塞的.

2017年10月1日 14:54