On Mon, 19 Jun 2000, you wrote:
> > De : Matt Sergeant [mailto:[EMAIL PROTECTED]]> 
> > On Mon, 19 Jun 2000, John Hughes wrote:
> > > (Hint - Perl passes all values by reference.
> > 
> > Are you sure thats the case with XS code?
> 
> Yes.

To expand on John's answer... :), and delve into where this thread started...:

In XS you just know how many variables are on the stack.  The only thing that
sits on the stack are pointers to SV's..., SV stands for "scalar value".  Now
as you might know, you can pass all sorts of things to XS functions, hashes,
arrays, etc.  So what happens is these things are "pushed" onto the stack of
execution, and the XS function is called.  It then peals things off of the
stack, and uses perl macros to find out what sort of reference it is.

To comment on what John originally said..., arg, here we go.  The difference
between print \$somevariable, and print $somevariable can be very significant. 
Everything is passed internally as a "reference", but that doesn't me it's done
in the same way.  When you say "print $somevar", and "print \$somevar" two VERY
different things happen.
case 1: print $somevar  (I'm assuming a type of string)
SV* somesv=(SV*)malloc(sizeof(SV));
somesv->sv_any=(void*)malloc(sizeof(char*)*strlen(ourstring)); //Notice, have
to set aside memory
strcpy((char*)somesv->sv_any,ourstring); //Notice we have to copy our data
-->Call the "print function" and pass it a reference to "somesv"

case2: print \$somevar
SV* somesv=(SV*)malloc(sizeof(SV)); //still need memory for this
somesv->sv_any=(void*)ourstring;
-->Call the "print function" and pass it a reference to "somesv"

Okay, so we need two less things to happen, we no longer need to set aside
memory for the string, and we don't have to copy it.  This is a big win in
terms of speed.  (Actually I think it happens quite a bit different internally,
but this is the "gist" of it.  There might even be one less SV malloc, because
it passes by "reference", it would have to create the reference which is an SV,
but it probably wouldn't have to create a second one like we need in case 1. 
Maybe Doug could help me out with this?)

So that's why when you pass by reference (and use it as such) it's 1) faster 2)
changes the value when it gets back to you, because it's not working from a
copy, it's working from the "real deal".  So if you're thinking of passing huge
strings, then it is in your best interest to pass by reference..., and if
you're passing hashes and arrays directly... SHAME ON YOU! :-) <Copying hashes
and arrays is NOT trivial... seriously>

Happy perling!
Shane.
(I tried to use less obfuscated c code..., sorry if I failed :-( )

Reply via email to