利用Redis緩衝提高斐波拉契數列程式的效能例子

來源:互聯網
上載者:User
去某家公司面試,PHP崗位,先做筆試,再兩輪面試,最後hr面,拿了offer。

 

筆試題都不難,做完隨手拍了一張,然後回去把這道求斐波那契數列的題在電腦上運行了一遍,寫的當然是對的,但是當你要求第N位,當N大於60的時候就會非常慢了,後來就想著用Redis緩衝來最佳化效能,效果非常驚人!

 

 

我把題目改了一下,也是要用遞迴,但是是要列出從0到n的斐波那契數列,並且用Redis緩衝。

 

思路很簡單,每次取第n的值的時候判斷Redis有沒有,有就不用再去計算了,沒有就計算一次存下來,大大減少計算次數。存的是hash結構。代碼如下:

 

在Laravel架構寫個控制器方法:


//斐波拉契數列
public function fib($n = null)
{
    if ($n > 100) {
        die('Number must <= 100!');
    }
    for ($i = 0; $i <= $n; $i++) {
        echo $this->getNum($i) . ' ';
    }
}
 
private function getNum($n)
{
    $key = 'com.tanteng.me.test.foo';
    $value = Redis::hget($key, $n);
    if ($value) {
        return $value;
    }
    if ($n == 0) $result = 1;
    if ($n == 1) $result = 1;
    if ($n > 1) {
        $result = $this->getNum($n - 2) + $this->getNum($n - 1);
    }
    Redis::hset($key, $n, $result);
    Redis::expire($key, 1800);
    return $result;
}


在routes.php檔案添加路由:

PHP


Route::get('/test/fib/{n?}', ['uses' => 'TestController@fib']);
通過瀏覽器訪問:http://www.111cn.net /test/fib/65

結果很快出來:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565 27777890035288

其中Redis存的內容如下:

 

如果不用Redis,求65個斐波那契數列就會很慢了,使用Redis幾乎是刷的一下就出來。在實際開發中,Redis也被廣泛使用,Redis真是個好東西

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.