javascript使用不可变字符串还是可变字符串?我需要一个“字符串生成器”吗?


当前回答

JavaScript字符串确实是不可变的。

其他回答

JavaScript字符串确实是不可变的。

Javascript中的字符串是不可变的

关于你的问题(在你对Ash的回复的评论中)关于ASP中的StringBuilder。NET Ajax专家们似乎不同意这一点。

Christian Wenz在他的书《编程ASP。NET AJAX (O'Reilly)说,“这种方法对内存没有任何可测量的影响(事实上,实现似乎比标准方法慢一点)。”

另一方面,Gallo等人在他们的书ASP。NET AJAX in Action (Manning),“当要连接的字符串数量较大时,字符串构建器就成为避免巨大性能下降的基本对象。”

我猜您需要自己进行基准测试,不同浏览器的测试结果也可能不同。然而,即使它不能提高性能,对于习惯于用c#或Java等语言编写StringBuilders的程序员来说,它仍然被认为是“有用的”。

来自犀牛的书:

In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings. Strings are assigned by reference, not by value. In general, when an object is assigned by reference, a change made to the object through one reference will be visible through all other references to the object. Because strings cannot be changed, however, you can have multiple references to a string object and not worry that the string value will change without your knowing it

只是为了澄清像我这样头脑简单的人(来自MDN):

不可变对象是一旦对象被创建,其状态就不能改变的对象。 字符串和数字是不可变的。

不可变意味着:

你可以让一个变量名指向一个新的值,但是之前的值仍然保存在内存中。因此需要垃圾收集。 var immutableString = "Hello"; //在上面的代码中,创建了一个string值的新对象。 immutableString = immutableString + "World"; //我们现在将"World"附加到现有值。

这看起来像是我们在改变字符串'immutableString',但我们没有。而不是:

在给"immutableString"附加一个字符串值时,会发生以下事件: 检索"immutableString"的现有值 "World"被附加到"immutableString"的现有值 然后将结果值分配给一个新的内存块 "immutableString"对象现在指向新创建的内存空间 以前创建的内存空间现在可用于垃圾收集。