PHP: Measure size in kilobytes of a object/array?

喜欢而已 提交于 2019-11-30 12:58:51

问题


  • What's an appropriate way of measure a PHP objects actual size in bytes/kilobytes?

Reason for asking:
I am utilizing memcached for cache storage in my web application that will be used by non-technical customers. However, since memcached has a maximum size of 1mb , it would be great to have a function set up from the beginning that I can be used to measure size of selected objects/arrays/datasets, to prevent them from growing to big.

Note that I am only planning on using this as a alert/diagnostic tool to keep track of the cache performance and storage possibilities over time. I assume that calculating speed on each memcached set/add call would slow down things a bit.

I am also aware of storing big datasets in memcached takes away the whole idea of storing things in the RAM, and that is exactly why I need to know in beforehand to prevent customers building up to big datasets.

Thanks a lot


回答1:


Well, since Memcached doesn't store raw objects (it actually stores the serialiezd version), you can do this:

$serializedFoo = serialize($foo);
if (function_exists('mb_strlen')) {
    $size = mb_strlen($serializedFoo, '8bit');
} else {
    $size = strlen($serializedFoo);
}



回答2:


Another easy way pute content of array to file and then check file size.

$str = print_r($array, true);
file_put_contents('data.txt', $str);
$size = filesize('data.txt');


来源:https://stackoverflow.com/questions/3072452/php-measure-size-in-kilobytes-of-a-object-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!