http://qs321.pair.com?node_id=795821


in reply to Converting a string to a real numeric value - what's faster?

First, whats meant by:

I ran into an issue that involved quite low-level transformations and as it turned out

To your comparison: The code sequence (*)

$string='7'; $num=$string+0
gives (*):
C:\>perl -MO=Concise,-exec -e"$string='7';$num=$string+0" 1 <0> enter 2 <;> nextstate(main 1 -e:1) v:{ 3 <$> const[PV "7"] s 4 <#> gvsv[*string] s 5 <2> sassign vKS/2 6 <;> nextstate(main 1 -e:1) v:{ 7 <#> gvsv[*string] s 8 <$> const[IV 0] s 9 <2> add[t4] sK/2 a <#> gvsv[*num] s b <2> sassign vKS/2 c <@> leave[1 ref] vKP/REFC

and the sequence (**)

$string='7'; $num=int($string)"

gives (**)

C:\>perl -MO=Concise,-exec -e"$string='7';$num=int($string)" 1 <0> enter 2 <;> nextstate(main 1 -e:1) v:{ 3 <$> const[PV "7"] s 4 <#> gvsv[*string] s 5 <2> sassign vKS/2 6 <;> nextstate(main 1 -e:1) v:{ 7 <#> gvsv[*string] s 8 <1> int[t4] sK/1 9 <#> gvsv[*num] s a <2> sassign vKS/2 b <@> leave[1 ref] vKP/REFC -e syntax OK
The Difference is (*)
8 <$> const[IV 0] s 9 <2> add[t4] sK/2
compared to (**)
8 <1> int[t4] sK/1

so there shouldn't be too much difference

Regards

mwa

Replies are listed 'Best First'.
Re^2: Converting a string to a real numeric value - what's faster?
by isync (Hermit) on Sep 17, 2009 at 09:50 UTC
    Thanks!
    What I learn from that is: if i am handling non-floating-point values, it's a bit more elegant and possibly a tick faster (one iteration less, 1-b vs 1-c) to use int(), otherwise the +0 trick isn't that much of a hack it seems to be.
      if i am handling non-floating-point values, it's a bit more elegant ... to use int()

      .. if it's worth the typed characters at all ;-)

      As you said before, Perl will convert the string into a number internally if the string isn't already converted (IV-Flag not set) and if the string is used in a numerical context.

      Of course, when using Perl-Guts (XS), you have to worry.

      regards

      mwa