21
  • 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

Industrial
  • 41,400
  • 69
  • 194
  • 289
  • See below the official manual page. http://php.net/manual/en/memcache.set.php And you will find "Parameters > var" section. > The variable to store. Strings and integers are stored as is, other > types are stored serialized. – Oh Seok-Geun Jul 24 '18 at 02:47

2 Answers2

34

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);
}
GitaarLAB
  • 14,536
  • 11
  • 60
  • 80
ircmaxell
  • 163,128
  • 34
  • 264
  • 314
  • Hi! That's just what I was about to ask. How does it handle UTF8 and multiple byte characters? – Industrial Jun 18 '10 at 19:32
  • 2
    Well, it all depends. If you have mb_string function overloading on, then you have issues. If not, `strlen` will return the byte length (which is what you want in the first place). If you have `mbstring.func_overload` on, you can use `mb_strlen(serialize($foo), '8bit');` in place of strlen. But note, mb_string must be installed to use it. I'll edit in a more robust version... – ircmaxell Jun 18 '10 at 19:42
  • Thanks a lot for your help ircmaxell! Great stuff – Industrial Jun 18 '10 at 19:42
  • @ircmaxell on line 5 of the script you have one too many paranthesis. (can't edit, because SO says edit must have at least 6 characters). – Jan Święcki Jan 05 '13 at 07:41
-1

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');
fdrv
  • 852
  • 1
  • 11
  • 21