Compartilhar via


Are JScript strings passed by reference?

Yesterday
I asked "are JScript strings passed by reference (like
JScript objects) or by value"urn:schemas-microsoft-com:office:office" /> (like
JScript numbers)?"

Trick
question! It doesn't matter, because
you can't change a string. I mean, suppose
they were passed by reference -- how would you know? You
can't have two variables refer to the "same" string and then change that string. Strings
in JScript are like numbers -- immutable primitive values.

Of
course, "under the covers" we actually have to pass the strings somehow. Generally
speaking, strings are passed by reference where possible, as it is much cheaper in
both time and memory to pass a pointer to a string than to make a copy, pass the value,
and then destroy the copy.

Comments

  • Anonymous
    September 17, 2003
    Thanks for the earlier reply. I think I get your point.Regarding your comment about having to pass strings somehow and generally doing it by reference "where possible", have you got an example of where it is not possible? Can I inadvertently cause my strings to be passed (slower) by value?Thanks!
  • Anonymous
    September 17, 2003
    Strings are pretty much always passed by reference, but often the first thing that the callee does is make a copy anyway. The script engines use BSTRs to store strings and BSTRs are not reference-counted, so any time the callee needs to, say, set a property, it needs to make a copy.I see what you're getting at though, and yes, there are plenty of times that you end up copying a lot of string data around. That's a good subject for tomorrow's post; I'll see if I can find any old email from a few years back when I did a lot of work in this area.
  • Anonymous
    May 31, 2004
    The comment has been removed
  • Anonymous
    May 31, 2004
    I suspect that you're confusing two different usages of the term "by reference". When I asked whether JScript strings were passed by reference, I meant whether the STRING ITSELF was passed by ref or by value. You're talking about whether the MEMORY ADDRESS that holds the string is passed by value or by reference, which is a subtly different thing.

    JScript passes objects by reference and numbers by value, but doesn't support passing references to variables at all.

    Confused? It's a confusing topic. I wrote an article about the difference here:

    http://blogs.msdn.com/ericlippert/archive/2003/09/15/53005.aspx