JavaScript字符串是不可变的吗?我需要JavaScript中的"字符串生成器"吗?
时间:2020-03-05 18:49:49 来源:igfitidea点击:
JavaScript是否使用不可变或者可变的字符串?我需要一个"字符串生成器"吗?
解决方案
回答
JavaScript字符串确实是不可变的。
回答
Javascript中的字符串是不可变的
回答
来自犀牛的书:
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
回答
性能提示:
如果必须连接大字符串,请将字符串部分放入数组中,并使用Array.Join()方法获取整个字符串。连接大量字符串的速度可能要快很多倍。
JavaScript中没有StringBuilder
。
回答
关于我们在ASP.NET Ajax中关于StringBuilder的问题(在对Ash的回应的评论中),专家似乎对此表示不同意见。
克里斯蒂安·温兹(Christian Wenz)在他的《 Programming ASP.NET AJAX(O'Reilly)》一书中说:"这种方法对内存没有任何可测量的影响(实际上,该实现似乎比标准方法稍慢一些")。
另一方面,Gallo等人在他们的书《 ASP.NET AJAX in Action(Manning)》中说:"当要连接的字符串数量较大时,字符串生成器将成为避免性能大幅下降的重要对象。"
我猜我们需要进行自己的基准测试,并且浏览器之间的结果也可能会有所不同。但是,即使它不能提高性能,对于习惯使用诸如Cor Java之类的StringBuilders进行编码的程序员来说,它仍然可能被认为"有用"。