开发者

No effect on efficiency in automatic conversion between numbers and strings?

There is automatic conversion between numbers and strings in Perl.

From the Llama book:

You don't need to worry about the difference between numbers and strings; just use the proper operators, and Perl will make it all work.

And if you're worried about efficiency, don't be. Perl generally remembers the result of a conversion so that it's don开发者_StackOverflow社区e only once.

How does this happens? I mean how does Perl remembers it and for how much time?

Doesn't it affect the efficiency even by a single bit?


Why should the efficiency be slower?

If you do the conversion automatically or manually, it is absolutely the same. But by doing it automatically you just need to type less code.

A scalar variable in perl can hold many different values. The runtime (perl interpreter) does a conversion and saves the number inside the scalar.

You can see such internal things with Devel::Peek

#!/usr/bin/env perl
use Devel::Peek;

my $value = '15';
Dump($value);
$value + 5;
Dump($value);
$value = 5;
Dump($value);

Output:

SV = PV(0x8f71040) at 0x8f82d88
  REFCNT = 1
  FLAGS = (PADMY,POK,pPOK)
  PV = 0x8f7ecb8 "15"\0
  CUR = 2
  LEN = 4
SV = PVIV(0x8f7a2fc) at 0x8f82d88
  REFCNT = 1
  FLAGS = (PADMY,IOK,POK,pIOK,pPOK)
  IV = 15
  PV = 0x8f7ecb8 "15"\0
  CUR = 2
  LEN = 4
SV = PVIV(0x8f7a2fc) at 0x8f82d88
  REFCNT = 1
  FLAGS = (PADMY,IOK,pIOK)
  IV = 5
  PV = 0x8f7ecb8 "15"\0
  CUR = 2
  LEN = 4

Here you can see that a Scalar Value (SV) has "15" the string as (PV), after doing an addition it adds (IV) (Integer Value).

A scalar contains a flags to know which value is correct. In the first dump you see the Flag POK that says PV is a correct current value. If you ask for this value, perl can immediately return this value.

After the addition you see "IOK" that says "IV" value is also okay. Actually the variable itself was not changed, but because an addition with a string was made perl needed todo a conversation from string to an int. What you see after the addition is that POK and IOK are valid. That means the Scalar currently holds a valid string and a valid Integer. As long as the variable doesn't change, both values are valid, and perl don't need to do a conversation.

But after changing the value to the integer 5 you see that "POK" is not set anymore. This operation sets the IV to a new value and invalidates the PV value. As long as you just work with $value as an integer nothing additional will happen. As soon as you use $value within a string context will will do a conversion to a string and will update PV and sets POK. But only has to do that once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜