【发布时间】:2014-05-24 12:59:54
【问题描述】:
我想知道使用 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等
- 哪种解决方案更有效?
- 还有其他最好的方法吗?
- 还有其他文件格式吗?
- 也许使用 PHP 数组而不是 json 文件和解析?
【问题讨论】:
-
没有办法回答这个问题。如果您将此代码代码调用一次,那么缓存就是浪费时间。如果您多次调用此代码,那么您必须权衡吸收大量内存以保存缓存数据,v.s.每次加载/解码 json 文件的时间节省。至于数组v.s。 json,请记住,一旦您解码 JSON,它就会变成 PHP 数组/字符串/对象/无论如何。
标签: php performance caching configuration