Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Delphi strings immutable?

As far as I know, strings are immutable in Delphi. I kind of understand that means if you do:

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

first string is destroyed and you get a reference to a new string "Hello World".

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

I have a string hash assigned for identifying several variables, so for example a "change" is identified by a hash value of the properties of that change. That way it's easy for me to check to "changes" for equality.

Now, each hash is computed separately (not all the properties are taken into account so that to separate instances can be equal even if they differ on some values).

The question is, how does Delphi handles those strings? If I compute to separate hashes to the same 10 byte length string, what do I get? Two memory blocks of 10 bytes or two references to the same memory block?

Clarification: A change is composed by some properties read from the database and is generated by an individual thread. The TChange class has a GetHash method that computes a hash based on some of the values (but not all) resulting on a string. Now, other threads receive the Change and have to compare it to previously processed changes so that they don't process the same (logical) change. Hence the hash and, as they have separate instances, two different strings are computed. I'm trying to determine if it'd be a real improvement to change from string to something like a 128 bit hash or it'll be just wasting my time.

Edit: Version of Delphi is Delphi 7.0

like image 715
Jorge Córdoba Avatar asked Apr 16 '09 12:04

Jorge Córdoba


People also ask

Which language string is immutable?

In Java, C#, JavaScript, Python and Go, strings are immutable.

What is string in Delphi?

A string represents a sequence of characters. Delphi supports the following predefined string types. String types. Type. Maximum length.

Are strings in Go immutable?

Go strings are immutable and behave like read-only byte slices (with a few extra properties). To update the data, use a rune slice instead. If the string only contains ASCII characters, you could also use a byte slice. See String functions cheat sheet for an overview of strings in Go.

Are strings in C immutable?

Yes they are different. It is true that the string literals themselves ( "hello" and "goodbye" ) are immutable.


1 Answers

Delphi strings are copy on write. If you modify a string (without using pointer tricks or similar techniques to fool the compiler), no other references to the same string will be affected.

Delphi strings are not interned. If you create the same string from two separate sections of code, they will not share the same backing store - the same data will be stored twice.

like image 50
Barry Kelly Avatar answered Oct 16 '22 19:10

Barry Kelly