PHP性能(读取配置)


PHP Performance (Read Configuration)

我想知道使用PHP使用内存空间和提高响应时间哪个更有效。

这里有以下代码:

解决方案01:每次从磁盘读取

<?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');
    }
}

解决方案02:将文件配置存储在类的属性中

<?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;
    }
}

现在想象一下,哪个用户请求myapp.local/admin/someaction/param/1/param/2,并且该操作消耗9个配置文件,大小分别为156155KB、86846KB、544646KB、8446KB、787587587KB等。

  1. 以下哪种解决方案更有效
  2. 还有其他最好的方法吗
  3. 还有其他文件格式吗
  4. 也许使用PHP数组而不是json文件和解析

这是一个经典的时间与空间权衡。没有普遍的答案,只有得到答案的好方法。

经验法则:

  1. 磁盘IO速度慢。解密和/或解压缩消耗周期。避免这种类型的重复工作通常会使程序运行得更快。

  2. 但是缓冲需要RAM。RAM是一种有限的资源。使用RAM加载处理器缓存。大量使用RAM会加载虚拟机系统。两者都会导致速度减慢,从而在一定程度上无法避免磁盘I/O。在极端情况下,加载虚拟机系统会导致磁盘交换,因此缓冲会导致磁盘IO

经验法则完成后,你必须使用良好的工程实践。

  1. 确定可用于在内存中保存磁盘数据的内存量
  2. 确定从磁盘重复读取哪些结构以及读取频率
  3. 确定它们的大小
  4. 选择一个有意义的集合:值最高的集合

    (每字节IO时间+每字节解压缩/解密时间)x读取频率x 大小(字节)

    也可以放入可用的RAM中。

  5. 实现4的缓存。正如你所提议的那样。

  6. 轮廓和测量。尝试其他选择。根据需要重复