Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Converting a string to a real numeric value - what's faster?

by mwah (Hermit)
on Sep 17, 2009 at 09:18 UTC ( #795821=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://795821]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2021-04-10 22:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?