字符串不可变有什么优势? [英] What's the advantage of a String being Immutable?

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

问题描述

我曾经研究过字符串可变的优点,因为它可以提高内存的性能.

Once I studied about the advantage of a string being immutable because of something to improve performace in memory.

有人可以向我解释吗?我无法在互联网上找到它.

Can anybody explain this to me? I can't find it on the Internet.

推荐答案

不可移植性(对于字符串或其他类型)具有许多优点:

  • 由于您可以对变量和参数进行假设,因此可以更轻松地对代码进行推理.
  • 它简化了多线程编程,因为从不能更改的类型读取始终可以安全地并发执行.
  • 通过允许将相同的值组合在一起并从多个位置引用,可以减少内存使用. Java和C#都执行字符串实习,以减少代码中嵌入的文字字符串的内存成本.
  • 它简化了某些算法(例如采用回溯或值空间分区的算法)的设计和实现,因为先前计算出的状态可以在以后重用.
  • 不可变性是许多功能编程语言的基本原理-它允许将代码视为从一种表示形式到另一种表示形式的一系列转换,而不是一系列的突变.
  • It makes it easier to reason about the code, since you can make assumptions about variables and arguments that you can't otherwise make.
  • It simplifies multithreaded programming since reading from a type that cannot change is always safe to do concurrently.
  • It allows for a reduction of memory usage by allowing identical values to be combined together and referenced from multiple locations. Both Java and C# perform string interning to reduce the memory cost of literal strings embedded in code.
  • It simplifies the design and implementation of certain algorithms (such as those employing backtracking or value-space partitioning) because previously computed state can be reused later.
  • Immutability is a foundational principle in many functional programming languages - it allows code to be viewed as a series of transformations from one representation to another, rather than a sequence of mutations.

不可变的字符串还有助于避免将字符串用作缓冲区的诱惑. C/C ++程序中的许多缺陷与缓冲区溢出问题有关,这些问题是由于使用裸字符数组来编写或修改字符串值而导致的.将字符串视为可变类型会鼓励使用更适合缓冲区操作的类型(请参见.NET或Java中的StringBuilder).

Immutable strings also help avoid the temptation of using strings as buffers. Many defects in C/C++ programs relate to buffer overrun problems resulting from using naked character arrays to compose or modify string values. Treating strings as a mutable types encourages using types better suited for buffer manipulation (see StringBuilder in .NET or Java).

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

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