Are Delphi strings immutable?

As far as I know, in Delphi strings are immutable. I understand that this means that you are doing:

string1 := 'Hello'; string1 := string1 + " World"; 

the first line is destroyed, and you get a link to a new line of "Hello World".

But what happens if you have the same line in different places around your code?

I have a hash string assigned to identify several variables, so, for example, a “change” is identified by the hash value of the properties of this change. This way, it’s easy for me to check the “changes” for equality.

Now each hash is calculated separately (not all properties are taken into account so that individual instances can be equal, even if they differ by some values).

The question is, how does Delphi handle these lines? If I figured out to separate hashes up to the same string 10 bytes long, what will I get? Two memory blocks of 10 bytes or two references to the same memory block?

Explanation:. The change consists of some properties read from the database and generated by a separate stream. The TChange class has a GetHash method that calculates a hash based on some values ​​(but not all), resulting in a string. Now the other threads receive the change and must compare it with the previously processed changes so that they do not process the same (logical) change. Therefore, the hash and, since they have separate instances, two different lines are computed. I am trying to determine if this will be a real improvement for moving from a string to something like a 128-bit hash, or will it just be wasting my time.

Edit: Delphi Version - Delphi 7.0

+6
string immutability memory delphi
source share
4 answers

Delphi strings are copied when writing. If you change the line (without using pointer tricks or similar methods to deceive the compiler), no other references to the same line will be affected.

Delphi strings are not interned. If you create the same line from two separate sections of code, they will not use the same storage: the same data will be saved twice.

+20
source share

Delphi strings are not immutable (try: string1 [2]: = 'a'), but they are counted by reference and copied to the record.

The consequences for your hashes are not clear, you will need to describe in detail how they are stored, etc.

But the hash should depend only on the contents of the string, and not on how it is stored. This makes the whole question dumb. If you can’t explain it better.

+4
source share
+2
source share

The Delphi version may be important for understanding. The good old Delphi BCL treats the lines as copy-on-write, which basically means that a new instance is created when something in the line changes. So yes, they are more or less unchanged.

0
source share

All Articles