Patrick
Patrick

Reputation: 4905

size (in KB) of variable in php

is it possible to calculate / estimate the size (in KB) of a variable (string, array but mostly array). What happen is that we store some data inside memcache, and we would like to know how much memory space that data would take inside memcache.

Upvotes: 6

Views: 15226

Answers (1)

six8
six8

Reputation: 2990

I believe PHP's memcache implementation uses serialize when storing in memcached. You can simply serialize the output and check it's size:

<?php
$data = array('foo' => 'bar');
$serialized_data = serialize($data);
$size = strlen($serialized_data);
# `strlen` returns number of chars in a string. Each char is 1 byte.
# So to get size in bits, multiply `strlen` results by 8. Divide by
# 1024 for KB or KiB. Divide by 1000 for kB.
print($size * 8 / 1000);
?>

Upvotes: 12

Related Questions