문제

I was wondering which is more efficient about use memory space and improve response time using PHP.

Here the following code:

Solution 01 : Read each time from the disk

<?php

class Resource
{

    // I know, but forget about validation and other topics like if isset($key) ... 
    public static function get($key)
    {
        $array = json_decode(static::getFile());
        return $array[$key];
    }

    // Imagine the get.json file has a size of 92663KB and is compress
    private static function getFile()
    {
        return file_get_contents('/var/somedir/get.json');
    }

}

Solution 02 : Store file configuration in an class's attribute

<?php

class Resource
{
    // This will be a buffer of the file
    private static $file;

    public static function get($key)
    {
        static::getFile();

        $array = json_decode(static::$file);
        return $array[$key];
    }

    // Imagine the get.json file has a size of 151515KB now and is compress
    private static function getFile()
    {
        if (!is_null(static::$file)) {
            static::$file = file_get_contents('/var/somedir/get.json');
        }

        return static::$file;
    }

}

Now imagine which a user ask for myapp.local/admin/someaction/param/1/param/2 and this action consume 9 configuration files with sizes of 156155KB, 86846KB, 544646KB, 8446KB, 787587587KB, etc.

  1. Which of this solutions is more efficient ?
  2. Is there are other best way to do this?
  3. Any other file format?
  4. Maybe use PHP arrays instead of json files and parsing?
도움이 되었습니까?

해결책

This is a classic time vs. space tradeoff. There is no universal answer, just good practice to get an answer.

Rules of thumb:

  1. Disk IO is slow. Decryption and/or decompression consume cycles. Avoiding repeated work of this type generally makes programs go faster.

  2. But buffering requires RAM. RAM is a limited resource. Use of RAM loads the processor cache. Very heavy use of RAM loads the VM system. Both cause slow-downs that partially defeat the avoidance of disk I/O. In the extreme, loading the VM system causes swapping to/from disk, so the buffering is causing Disk IO.

After the rules of thumb are done, you must use good engineering practice.

  1. Determine how much memory you can dedicate to holding disk data in memory.
  2. Determine which structures are read repeatedly from disk and how often.
  3. Determine their sizes.
  4. Choose a set that makes sense: those with the highest value of

    (IO time per byte + Decompress/decrypt Time per byte) x FrequencyOfReads x Size in bytes

    that also fit in available RAM.

  5. Implement caching of 4. as you have proposed.

  6. Profile and measure. Try alternatives. Repeat as needed.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top