Does it make sense to copy an immutable type?

Does it make sense to implement a copy method on an immutable type, returning a new instance? Or is it just the current instance?

I thought the type does not change, so why copy? Like no one is copying number 5, right?

+5
source share
6 answers

There are certain cases where this makes sense. Java strings are a good example. When a string is created in Java, it refers to an array of character substitution (a char[]). He knows the offset in the char array and the length of the string. When you create a substring, it refers to the same base array. Now consider this code:

String x = buildVeryLongString();
String y = x.substring(0, 5);
// Use y a lot, but x is garbage collected

, y , , char[], x, - . , , . :

String x = buildVeryLongString();
String y = new String(x.substring(0, 5));

char[]. x y , ( ), , x - y, .

, . BufferedReader.readLine() 80 , ( ) , readLine(), char[] 80 . , !

, , , , . , , , .

.NET - , . (, IntPtr .NET, .) "" , . :

StringBuilder builder = new StringBuilder(10000);
builder.Append("not a lot");
string x = builder.ToString();

, x, . builder.ToString().Copy() , . , - , .

+12

, .:)

, . , , , .

+4

, (), .

:

  • , ( , , , - clone ( ))
  • ( readonly ) - ,
  • - API ( ) , "", - , ...

, , , , . , .

, , - , ...

+3

Java String :

String(String original)
      Initializes a newly created String object so that it represents the same 
      sequence of characters as the argument; in other words, the newly created 
      string is a copy of the argument string.

.Net Copy(), .

, , - - - , - , .

, ...

+2

"", ?

.

( , , .)

, Clone() ( ), " ".

+2

One advantage of immutable types is that they can be interned (like Java strings). Of course, you should not make extra copies if you can avoid this.

0
source

All Articles