德尔福字符串是不可变的吗? [英] Are Delphi strings immutable?

查看:120
本文介绍了德尔福字符串是不可变的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,字符串在Delphi中是不可变的。我很明白,如果你这样做:

  string1:='你好' 
string1:= string1 +World;

第一个字符串被销毁,您可以引用一个新的字符串Hello World。



但是如果你的代码中的不同地方有相同的字符串,会发生什么?



我有一个字符串哈希值识别几个变量,因此例如更改由该更改的属性的哈希值标识。这样我很容易检查变化的平等。



现在,每个散列都是单独计算的(并非所有的属性都被考虑在内,以便分开实例可以相等,即使它们在某些值上有所不同)。



问题是,Delphi如何处理这些字符串?如果我计算将哈希值分隔成相同的10个字节长度的字符串,我该怎么做?两个内存块,10个字节或两个引用到同一个内存块?



澄清:更改由从数据库读取的某些属性组成并由单独的线程生成。 TChange类有一个GetHash方法,它基于字符串产生的一些值(但不是全部)来计算哈希。现在,其他线程接收到Change,并且必须将其与之前处理的更改进行比较,以使它们不处理相同(逻辑)更改。因此,散列,并且由于它们具有单独的实例,所以计算出两个不同的字符串。我试图确定是否真正改进字符串到128位散列,或者只是浪费我的时间。



编辑:Delphi的版本是Delphi 7.0

解决方案

Delphi字符串是复制的。如果您修改一个字符串(不使用指针技巧或类似技术来愚弄编译器),则不会影响到对同一字符串的其他引用。



Delphi字符串不被内联。如果您从两个独立的代码段创建相同的字符串,它们将不会共享同一个后台存储 - 相同的数据将被存储两次。


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

解决方案

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.

这篇关于德尔福字符串是不可变的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆