- Getting size in memory of an object in PHP?
- 5 Answers 5
- sizeof
- Saved searches
- Use saved searches to filter your results more quickly
- License
- mrsuh/php-var-sizeof
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- Getting length of var and creating a width
- PHP sizeof() Function
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
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.
5 Answers 5
You can call memory_get_usage() before and after allocating your class as illustrated in this example from IBM. You could even create a wrapper to do this, possibly storing the result on a member variable of the complex class itself.
To clarify the part about storing the allocated memory size, you can do something like this:
class MyBigClass < var $allocatedSize; var $allMyOtherStuff; >function AllocateMyBigClass() < $before = memory_get_usage(); $ret = new MyBigClass; $after = memory_get_usage(); $ret->allocatedSize = ($after - $before); return $ret; >
At any point in the future, you could check allocatedSize to see how big that object was at time of allocation. If you add to it after allocating it, though, allocatedSize would no longer be accurate.
What if PHP decides to free the memory that was kept allocated, just at the «wrong time» ? I don’t really know when PHP frees memory (kind of «when needed», I suppose), but I’m guessing this freeing could bring some problems ? Especially with the garbage collector introduced by PHP 5.3 for cyclic-references ?
Well yeah, but in addition to what Pascal mentioned, I want to be able to find this out at different times, not just at allocation time. I want to find this out many lines down the road.
@Pascal: PHP will not free memory that’s still referenced by an object actively being used. Cyclic references means A references B and B references A, but nothing else references either A or B. So memory will not be freed as long as the program can still reference it in any way.
@Artem: I mentioned in my post that you could keep the allocated size as part of your data structure. I’ll edit the post now to make that clearer.
Is not reliable. Have tested with simpleXML and printing memory before and after load + tested with memory_get_peak_usage on xml-files of several megabytes (on php 5.5).
Would it not make sense to try serializing the object and reading the string length? Obviously it will be several bytes off because serialized string would have s:’string’ therefore s:» being extra bytes. unless serialize could be the same way that PHP stores objects.
$size = strlen(serialize($object));
Another messy but possibly accurate thought:
Assuming a class instance variable that has been manipulated a few times since instantiation:
$DB; // database access class for eg. $mem = memory_get_usage(); $DB_tmp = clone $DB; $mem = memory_get_usage() - $mem; unset($DB_tmp);
$mem could be the exact amount of memory allocated to $DB;
I don’t think this is quite possible ; I’ve never seen anything that would allow you to get the size of an object in memory.
A solution to get a pretty rough idea might be to kind of serialize your data, and use strlen on that. But that will really be something of an estimation. I wouldn’t quite rely on anything like that, actually.
Even debug_zval_dump doesn’t do that : it ouput the data in a variable and the refcount, but not the memory used :
$obj = new stdClass(); $obj->a = 152; $obj->b = 'test'; echo '
'; debug_zval_dump($obj); echo '';
object(stdClass)#1 (2) refcount(2) < ["a"]=>long(152) refcount(1) ["b"]=> string(4) "test" refcount(1) >
sizeof
I am quite surprised about previous posts. Here are my advices:
1/ prefer the count() function instead of sizeOf() as sizeOf() is only an alias of count() and does not mean the same in many other languages based on C (avoid ambiguity).
2/ prefer the powerful forEach() function to iterate over arrays.
I would recommend not using sizeof(). Many programmers expect sizeof() to return the amount of memory allocated. Instead sizeof() -as described above- is an alias for count().
Prevent misinterpretation and use count() instead.
It is reccomended to set a variable first for this case:
a) Always try and use PHP’s internal routines to iterate through objects of various types (arrays in most examples below).
Instead of interpreting your code to loop through them, they use their own internal routines which are much faster.
(This is why foreach () will run faster than manual interation)
b) It is _always_ good practice to leave as many static resulting functions outside of loops, having operations that return the exact same piece of data every iteration of the loop is not pretty on resources.
c) I agree with PixEye’s remarks on sizeof(). In PHP it is just an alias for the true function count(). It has other meanings logically in other languages rather than the number of elements in an object. This should be avoided as it may confuse developers transitioning to PHP from other languages.
- Функции для работы с массивами
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_is_list
- array_key_exists
- array_key_first
- array_key_last
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
- each
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Function for getting size of any PHP variable in bytes
License
mrsuh/php-var-sizeof
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Function for getting size of any PHP variable in bytes.
It must be more accurate tool to calculate total size of PHP variable than memory_get_usage() , but it has restrictions.var_sizeof() with var_class_sizeof() uses FFI to access internal structures of PHP variables.
It calculates the size of internal structures such as zval , _zend_array , _zend_object , etc., as well as additional allocated memory for them.
It doesn’t take into calculate the memory of handlers/functions/etc.composer require mrsuh/php-var-sizeof
int var_class_sizeof(mixed $var);
require_once __DIR__ . '/vendor/autoload.php'; $int = 1; printf("variable \$int size: %d bytes\n", var_sizeof($int)); $array = array_fill(0, 100, $a); printf("variable \$array size: %d bytes\n", var_sizeof($array)); $object = new \stdClass(); printf("variable \$object size: %d bytes\n", var_sizeof($object)); printf("class \$object size: %d bytes\n", var_class_sizeof($object));
var_sizeof vs memory_get_usage
type var_sizeof(bytes) memory_get_usage(bytes) NULL 16 0 boolean(true) 16 0 integer(1) 16 0 double(1.5) 16 0 string(«hello world») 27 40 resource 48 416 callable 72 384 array(count: 0, list: true) 336 0 array(count: 100, list: true) 2,128 8,248 array(count: 1,000, list: true) 16,464 36,920 array(count: 10,000, list: true) 262,224 528,440 array(count: 100, list: false) 5,192 8,248 array(count: 1,000, list: false) 41,032 41,016 array(count: 10,000, list: false) 655,432 655,416 EmptyClass<> 72 40 ClassWithArray 408 56 ClassWithArray 2,200 8,304 ClassWithArray 16,536 36,976 ClassWithArray 262,296 528,496 ClassWithObject»> 144 96 ArrayIterator 2,264 8,376 ArrayIterator 5,328 40,376 type var_class_sizeof(bytes) var_sizeof(bytes) memory_get_usage(bytes) EmptyClass<> 1,362 72 40 ClassWithArray 1,494 408 56 ClassWithArray 1,494 2,200 8,304 ClassWithArray 1,494 16,536 36,976 ClassWithArray 1,494 262,296 528,496 ClassWithObject»> 1,495 144 96 ArrayIterator 2,437 2,264 8,376 ArrayIterator 2,437 5,328 40,376 - works correctly only with userland objects and SPL \ArrayIterator
- doesn’t work correctly with complicated structures like extensions/resources/callables/functions
- to calculate total size of an object you need to use var_sizeof() with var_class_sizeof()
How to reproduce a table of numbers above
git clone --recurse-submodules git@github.com:mrsuh/php-var-sizeof.git && cd php-var-sizeof composer install docker build -t image-php-var-sizeof . docker run -it --rm --name my-running-script -v "$PWD":/app image-php-var-sizeof php bin/render-table.php
cd php-src ./buildconf ./configure cd .. make DEBUG=1
Getting length of var and creating a width
I have a banner background that is complex and the text blends into it so I need to add a background to this div so it shows the text given. Is there a way using PHP that I can get the length of the text and turn it into a px so I then can use it to set a width on the div? Its the entry-title that I want to be automatic HTML:
function avada_page_title_bar( $title, $subtitle, $secondary_content ) < global $smof_data; $post_id = get_queried_object_id(); // Check for the secondary content $content_type = 'none'; if ( strpos( $secondary_content, 'searchform' ) !== FALSE ) < $content_type = 'search'; >elseif ( $secondary_content != '' ) < $content_type = 'breadcrumbs'; >// Check the position of page title if ( metadata_exists( 'post', $post_id, 'pyre_page_title_text_alignment' ) && get_post_meta( get_queried_object_id(), 'pyre_page_title_text_alignment', TRUE ) != 'default' ) < $alignment = get_post_meta( $post_id, 'pyre_page_title_text_alignment', TRUE ); >elseif ( $smof_data['page_title_alignment'] ) < $alignment = $smof_data['page_title_alignment']; >// Render the page title bar echo sprintf( '
', $content_type, $alignment ); echo ''; > >'; echo ''; echo ''; echo ''; echo ''; if( $title ) < // Add entry-title for rich snippets $entry_title_class = ''; if ( ! $smof_data['disable_date_rich_snippet_pages'] ) < $entry_title_class = ' '; >echo sprintf( '%s', $entry_title_class, $title ); if ( $subtitle ) < echo sprintf( ''; // Render secondary content on left/right layout if ( $alignment != 'center' ) < if ( fusion_get_option( 'page_title_bar_bs', 'page_title_breadcrumbs_search_bar', $post_id ) != 'none' ) < echo '%s
', $subtitle ); > > // Render secondary content on center layout if ( $alignment == 'center') < if ( fusion_get_option( 'page_title_bar_bs', 'page_title_breadcrumbs_search_bar', $post_id ) != 'none' ) < echo ''; echo $secondary_content; echo ''; > > echo ''; echo $secondary_content; echo ''; > > echo 'PHP sizeof() Function
The sizeof() function returns the number of elements in an array.
The sizeof() function is an alias of the count() function.
Syntax
Parameter Values
- 0 — Default. Does not count all elements of multidimensional arrays
- 1 — Counts the array recursively (counts all the elements of multidimensional arrays)
Technical Details
More Examples
Example
Count the array recursively:
echo «Normal count: » . sizeof($cars).»
«;
echo «Recursive count: » . sizeof($cars,1);
?>COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.