in reply to (OT) Re^7: Snarky comments on the ddj perl quiz
in thread Snarky comments on the ddj perl quiz

Our thread, for us to use and abuse as any of us see fit.

Did you know that:

$x = "1.1"; $y = 0+$x;
leaves $x taking less memory than
$x = 1.1; $y = "$x";
?

Replies are listed 'Best First'.
(OT) Re^9: Snarky comments on the ddj perl quiz (hijack, pvnv memory)
by Argel (Prior) on Aug 30, 2007 at 23:08 UTC
    LOL!! No I didn't and asking why is certainly worthier than some of those DDJ questions! Okay, so I'll bite -- why does it use less? I really do not know enough about perl to answer that one and my C is getting very rusty. Still, I doubt a three element char* uses more memory than a float so this sounds like a Perl-ism. Does perl end up storing a numerical and a string version in the second example while just converting from a string to a numeric in the first example? Or put differently, does the first example give perl a better hint? Is this part of the Perl spec or just a side effect of the perl implementation?
      Both store both the integer and character value. But one uses a 4-byte string buffer and one (for reasons unknown to me, but perhaps related to the longest conceivable stringification of a floating point number) uses a 36-byte string buffer.
        Ahh, I see. In the first example the length is known because "1.1" is a constant so storing it can be optimized while in the second example "$x" to evaluated at runtime.