Is specifying an encoding in BinaryStream.Read the same as calling DefineEncoding or ConvertEncoding?

Hi,

With a BinaryStream.Read call, we can pass an optional parameter for an encoding. In my case, I need to decide later whether I want to apply an encoding or leave it “unencoded”.
Given the difference between ConvertEncoding and DefineEncoding, I’m guessing calling BinaryStream.Read with the encoding parameter would be equal to DefineEncoding (that is, from “no encoding” to an encoding) and, with calling BinaryStream.Read without the parameter and setting the encoding later, I should use the DefineEncoding function, not the ConvertEncoding one (since there’s still no encoding to the source).

Is it a correct guess and is there another difference between specifying the encoding right in the Read call and specifying later using DefineEncoding?

That’s correct. In your case, you would not use ConvertEncoding until you had defined an encoding using one of those avenues.

Since strings are immutable, defining or converting encoding will create a second copy of the string with the specified encoding, then tear down the first copy if it’s no longer being referenced. I’d hope that defining the encoding through the Read does something more efficient, but don’t know (just like I don’t know if there is some optimization for DefineEncoding of which I’m unaware), but that would be the only difference.

1 Like

DefineEncoding should only change the string’s metadata, Shirley? Why would that require copying it?

Strings are immutable, including their encoding.

Thanks for your answers. I’ll consider both as being similar.

If so, aren’t they constants ?

No.

The original one could be considered “constant”, in the sense that it won’t change (not in the sense of a Xojo constant). But since it disappears and gets replaced by the converted one, the actual string referenced by your variable isn’t technically the same.

1 Like

Are they immutable or not ?

wikipedia says:

and immutable have the same meaning…

Where is my hat ?

Consider this example:

Var s as string

s=SomeStringObtainedByASourceWithoutEncoding()
s=s+"Another string"
s=s.DefineEncoding(Encodings.UTF8)

(see below)

You can see “s” has varied twice, in the code above. So “s” isn’t a constant.

Not sure it’s the same. I’m reading this:
“not able to be altered in the memory after its value is set initially”.

In regard to this definition, one may think a string variable is mutable. However, in Xojo, altering a string makes a copy of that string (that’s another storage place in memory).

In other words (and as I understand it), “immutable” refers to the “in memory” content, where modifying a string makes a copy of it to another location, while a “constant” is about the variable (“s” in the examples above), which is at the code side and can represent several locations in RAM (at different times, of course).

1 Like