Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why only string is immutable & not other data types

Tags:

c#

vb.net

I always wonder when it comes to mutability. Why .net designers have developed only stringbuilder class to achieve mutability of string class & not intbuilder for int considering int & string are implemented exactly the same way irrespective of their data types.

like image 638
Ulhas Tuscano Avatar asked Nov 11 '22 02:11

Ulhas Tuscano


1 Answers

Many other languages provide similar design for strings: Java with StringBuffer and StringBuilder, Scala with StringBuilder, Python with MutableString though there are other, beter solutions in Python. In C++ strings are mutable, so no need for a builder.

The reason why builder exist for strings is:

  1. Many languages define string as immutable (any change requires a new object in memory)
  2. Strings tend to be large, much larger than ints
  3. [1] and [2] combined cause inefficiency

The reason why builder doesn't exist for int:

  1. It is simple data structure by itself
  2. Most CPU have optimised instructions to deal with simple numbers (add, take away, etc)
  3. Most CPU would efficiently process [2] instructions in just one or a few cycles, using registers or fast CPU cache
  4. [2] and [3] combined remove the need for optimisation
  5. There is little need to mutate an int per se, however, if you need to, you can use BitConverter or binary shift operations
like image 60
oleksii Avatar answered Nov 14 '22 22:11

oleksii