Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

  • 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

like image 713
Industrial Avatar asked Jun 18 '10 19:06

Industrial


People also ask

How do I get the size of an array in PHP?

There are two common ways to get the size of an array. The most popular way is to use the PHP count () function. As the function name says, count () will return a count of the elements of an array.

What is sizeof () function in PHP?

The sizeof() function is a builtin function in PHP and is used to count the number of elements present in an array or any other countable object.

How to get size in memory of an object in PHP?

Getting size in memory of an object in PHP? There is a way to get the total memory PHP is using ( memory_get_usage ()) but how does one get the size in memory of an individual object? I'm obviously not talking about count () as I want the number of bytes in a potentially complex data structure.

How to define your own array keys in PHP?

In PHP, Array keys start at 0 For even more control, arrays also allow you to define your own array keys, using a string. $post_data = array ('heading' => 'PHP Array Length Tutorial', 'subheading' => 'How to get an array size', 'author' => 'Jonathan Bossenger'); This allows you to also reference the array item by its string key.


1 Answers

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); } 
like image 90
ircmaxell Avatar answered Sep 25 '22 01:09

ircmaxell