Reputation: 159
Is there any difference in php 5.* between
1. $variable = (int) 1111;
vs.
2. $variable = '1111';
in terms of physical resources eg. memory usage.
Please any ideas.
Upvotes: 3
Views: 77
Reputation: 14071
If we take into consideration what the following page says:
It should be clear from the structures above that a variable can be of one type, the variable data is represented by the appropriate field in the zval_value union.
That means the answer to your question is: YES. There is a difference in the amount of memory used based on what the variable really is represented as internally.
The comments under your question are tackling other issues, such as viability etc. so I will refrain from dealing with that.
Upvotes: 3
Reputation: 522125
A (ASCII) string uses 1 byte per character. An int is a fixed length regardless of its value. For "1111" on a 32 bit system, both happen to take up 4 bytes. On 64 bit systems the int will take 8 bytes, while the string won't change.
Ints can store a value up to 9223372036854775807 on 64 bit systems in 8 bytes. To store the same number in a string, you'd use 19 characters = 19 bytes. Strings can store arbitrarily long numbers, ints have a finite limit.
This is ignoring any overhead PHP's internal zval representation may add for different types.
However, unless you need to cram millions and millions of numbers into memory at once (at which point PHP may be the wrong tool for the job you're trying to do), it hardly makes any difference. Use ints for numeric values, use strings for text. Unless you need to store numbers which do not fit in an int, then use a string. That should be the primary concern.
Upvotes: 2
Reputation: 436
Altough this is a bit unprecise (it will depend on yhour system settings), you can try this
<?php
$variable = '1111111111';
echo memory_get_usage();
?>
(You''l have to reload your page a couple of times until you get a stable result)
Upvotes: 1