C#: practical value of string.Copy(string) method

Status
Not open for further replies.

DavlinLotze

Ars Scholae Palatinae
830
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Jackass JoeJoe:<BR>When you reference a string and it is replaced, what happens to other variables referencing the same string? </div></BLOCKQUOTE><BR>They retain their values:<BR><pre class="ip-ubbcode-code-pre"> string a = "Hello, Abe!";
string b = a;
b = "Hello, Bob!";
gSCon.WriteLine(a); // "Hello, Abe!"
gSCon.WriteLine(b); // "Hello, Bob!"</pre>
 
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by DavlinLotze:<BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Jackass JoeJoe:<BR>When you reference a string and it is replaced, what happens to other variables referencing the same string? </div></BLOCKQUOTE><BR>They retain their values:<BR><pre class="ip-ubbcode-code-pre"> string a = "Hello, Abe!";
string b = a;
b = "Hello, Bob!";
gSCon.WriteLine(a); // "Hello, Abe!"
gSCon.WriteLine(b); // "Hello, Bob!"</pre> </div></BLOCKQUOTE><BR><BR>Shouldn't you be changing "a" for this test to make any sense?
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Jackass JoeJoe:<BR>When you reference a string and it is replaced, what happens to other variables referencing the same string? </div></BLOCKQUOTE>If you could do that, the string isn't immutable.
 
The reason for this is to help you reduce memory usage from large strings that are kept around.<BR><BR>For example, say you have:<BR><BR><pre class="ip-ubbcode-code-pre">
string s = "some really ... long string";
string t = s.Substring(0, 4);
</pre><BR><BR>The runtime is free to implement the above substring as a very think wrapper on top of the original string. i.e. it could be written like so:<BR><BR><pre class="ip-ubbcode-code-pre">
class String {
private readonly char[] charArray;
private readonly int start;
private readonly int length;

private Substring(char[] charArray, int start, int length) {
this.charArray = charArray;
this.start = start;
this.length = length;
}

string Substring(int from, int length) {
// todo, check indices
return new String(charArray, start + from, length);
}
</pre><BR><BR>So this allows 'Substring' to be extremely fast. It doesn't need to do any copies, but instead is just a single object allocation that hten points to the same underlyign data.<BR><BR>Unfortunately, this can be really bad in some scenarios. You load up several large files but only want to hold onto a few bits of data from each, etc. etc.<BR><BR>So String.Copy addresses that. By making a copy, you then only get a string that holds onto what it needs, and the larger strings can get freed up.
 

DavlinLotze

Ars Scholae Palatinae
830
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Metasyntactic:<BR>So String.Copy addresses that. By making a copy, you then only get a string that holds onto what it needs, and the larger strings can get freed up. </div></BLOCKQUOTE><BR><BR>So because of the way the string class is implemented, you can end up with the equivalent of uncollected garbage? (A string remains only because it's referenced by another string. There's never an automatic refactoring of strings to remove unused references.)<BR><BR>So any time I'm using Substring() (or stuff like Split, Trim, etc.), I should consider the possible down-the-road memory benefit of enclosing it in string.Copy()?<BR><BR>If I use string.Copy(string) to make an exact copy of a string, will the strings be automatically interned, or is interning always explicit? (I'm just now learning about string interning.) Does string.Copy() give you an uninterned copy of an interned string?
 
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by DavlinLotze:<BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Metasyntactic:<BR>So String.Copy addresses that. By making a copy, you then only get a string that holds onto what it needs, and the larger strings can get freed up. </div></BLOCKQUOTE><BR><BR>So because of the way the string class is implemented, you can end up with the equivalent of uncollected garbage?<BR> </div></BLOCKQUOTE><BR>No. Garbage should almost always be collected**. However, in the case i showed above, the char array is not garbage. It is being referenced, so it is rightfully kept around.<BR><BR>Now, that said, you may end up with unexpected cases where you're holding onto more memory than you anticipated.<BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content"><BR> (A string remains only because it's referenced by another string. There's never an automatic refactoring of strings to remove unused references.)<BR> </div></BLOCKQUOTE><BR>There may or may not be. The above code i wrote may not even be true. It can vary with every version of the .Net runtime. String.Substring is free to do whatever it wants under the covers. <BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content"><BR>So any time I'm using Substring() (or stuff like Split, Trim, etc.), I should consider the possible down-the-road memory benefit of enclosing it in string.Copy()?<BR> </div></BLOCKQUOTE><BR>Not really no. You should do whatever is more natural and clear. And then you should test the performance. If there is actually a problem, only then should you do something about it.<BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content"><BR>If I use string.Copy(string) to make an exact copy of a string, will the strings be automatically interned, <BR> </div></BLOCKQUOTE><BR>The documentation doesn't say, so there is no way to know.<BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content"><BR>or is interning always explicit? <BR> </div></BLOCKQUOTE><BR>Again, the documentation doeesn't specify, so one cannot say. <BR><BR>Remember that this is just API documentation. Different implementations can, and will, do different things.<BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content"><BR>(I'm just now learning about string interning.) Does string.Copy() give you an uninterned copy of an interned string? </div></BLOCKQUOTE>Well, it says it's a copy, ergo it's not the same string.<BR><BR>But you can easily test this if you want:<BR><BR>string a = GenerateAStringSomehow();<BR>string b = a.Intern();<BR>string c = string.Copy(b);<BR>Console.WriteLine(Same String? " + object.ReferenceEquals(b, c));<BR><BR>Feel free to report back whatever you discover.<BR><BR>--<BR><BR>** GC is a very interesting place with lots of nooks and crannies for exceptional circumstances to hide within. But, in general, if your code is not doing anything exceptionally weird, then it should be the case that garbage is collected. YMMV of course.
 
BTW davlin, i want to highlight something important in what i wrote above:<BR><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">The runtime is free to implement the above substring as a very think wrapper on top of the original string. i.e. it <B>could</B> be written like so: </div></BLOCKQUOTE><BR><BR>I'm not saying how it's actually written. I'm only saying one of the many possible ways that it might have been written. The implementation can do whatever it wants as long as it matches the API. That means the developers may or may not have traded off many different things when implementing it. Perhaps they wanted to avoid this problem, and so they copy whenever you do substring. Perhaps they liked the above style and only point a new object at the existing backing store. The different approaches have differing benefits and drawbacks.
 

DavlinLotze

Ars Scholae Palatinae
830
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Metasyntactic:<BR>No. Garbage should almost always be collected**. However, in the case i showed above, the char array is not garbage. It is being referenced, so it is rightfully kept around. </div></BLOCKQUOTE><BR>Right. I realize it's not technically garbage - just "the equivalent of" garbage (from the programmer's perspective, since he can't directly control how the .NET runtime stores the string).<BR><BR>Thanks for pointing out that the CLR can be implemented many different ways, and that the specs leave lots of room for variations. That's something I need to remember so I don't let <I>possible</I> implementation dictate how I write code. I have a tendency to get anal about minor performance advantages and make my code less readable and very micro-managed. .NET is more about cross-platform porting and a big API than efficiency.
 
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by DavlinLotze:<BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Metasyntactic:<BR>No. Garbage should almost always be collected**. However, in the case i showed above, the char array is not garbage. It is being referenced, so it is rightfully kept around. </div></BLOCKQUOTE><BR>Right. I realize it's not technically garbage - just "the equivalent of" garbage (from the programmer's perspective, since he can't directly control how the .NET runtime stores the string).<BR> </div></BLOCKQUOTE><BR>That's not a very good perspective to take though. The majority of classes and systems in the .Net work don't let you directly control anything. If your perspective on things is that that makes them garbage, then you'll find things rather difficult to deal with. <BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content"><BR>Thanks for pointing out that the CLR can be implemented many different ways, and that the specs leave lots of room for variations. That's something I need to remember so I don't let <I>possible</I> implementation dictate how I write code. I have a tendency to get anal about minor performance advantages and make my code less readable and very micro-managed. .NET is more about cross-platform porting and a big API than efficiency. </div></BLOCKQUOTE>Actually, it can very much be about efficiency. It's just about measuring efficiency in different ways. <BR><BR>If you're going to care about performance, you should do it the right way. With actual data and a scenario you are trying to solve. <img src="http://episteme.arstechnica.com/groupee_common/emoticons/icon_smile.gif" alt="Smile" width="15" height="15">
 

fitten

Ars Legatus Legionis
55,636
Subscriptor++
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by DavlinLotze:<BR>That's something I need to remember so I don't let <I>possible</I> implementation dictate how I write code. I have a tendency to get anal about minor performance advantages and make my code less readable and very micro-managed. </div></BLOCKQUOTE><BR><BR>Be very, very, very, very, very, very, very careful here. I cannot remember all the times I've seen WTF code somewhere that was put into place because someone was trying to micromanage something for 'performance' reasons and ended up with not only poorer performing code, but broken code. And not only was it slower (and maybe broken), it was a nightmare to maintain, completing the trifecta. And on top of that, it was in a place that *simply did not matter*. Speeding up that particular bit of code may be spending lots of time optimizing something that is rarely, if ever, used and even when it is, it still wouldn't matter if you doubled its performance.<BR><BR>Write, test, profile, then optimize if necessary. Outside of certain application kernels, optimization to those levels are typically, and simply, not needed.<BR><BR>Note: I'm not advocating writing slow code. I'm advocating writing *good* code (where "good" has a large helping of maintainability).
 
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Metasyntactic:<BR>That's not a very good perspective to take though. The majority of classes and systems in the .Net work don't let you directly control anything. If your perspective on things is that that makes them garbage, then you'll find things rather difficult to deal with. </div></BLOCKQUOTE><BR>To me, garbage is data that your program will never be able to access (either directly or indirectly). Suppose you create a string, substring it, then dereference the initial string, and the substring references the original character array. Then the portions of the character array that aren't part of the substring will never be accessible (at least without some major hackery, at which point all correctness bets are off), and therefore it is garbage.
 
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by fitten:<BR>Be very, very, very, very, very, very, very careful here. I cannot remember all the times I've seen WTF code somewhere that was put into place because someone was trying to micromanage something for 'performance' reasons and ended up with not only poorer performing code, but broken code. And not only was it slower (and maybe broken), it was a nightmare to maintain, completing the trifecta. And on top of that, it was in a place that *simply did not matter*. Speeding up that particular bit of code may be spending lots of time optimizing something that is rarely, if ever, used and even when it is, it still wouldn't matter if you doubled its performance.<BR><BR>Write, test, profile, then optimize if necessary. Outside of certain application kernels, optimization to those levels are typically, and simply, not needed.<BR><BR>Note: I'm not advocating writing slow code. I'm advocating writing *good* code (where "good" has a large helping of maintainability). </div></BLOCKQUOTE><BR>Adding to this, copying strings to save memory is a specialized task and should not usually be done. It's for the situation where you substring long strings, discard the long strings, and keep around the small strings, which does inevitably occur in the real world but is fairly uncommon.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">therefore it is garbage. </div></BLOCKQUOTE><BR><BR>Whilst this sounds like a useful thought process it is not, from the point of view of the runtime correct.<BR>As an example of existing behaviour with equivalent effect:<BR><BR>When using StringBuilder the algorithm for growing the backing array is to double[1] in size.<BR>When ToString is called on it it does not, by default strip off any excess length, it leaves them there avoiding an additional copy but possibly wasting a bit of space, a classic time/space trade off[2].<BR><BR>This excess is not garbage, to the GC, it is referenceable, and easily accessible by perfectly legal reflection. <BR>It could be *converted* into garbage by some code spotting such excess and swapping the underlying array away underneath it for one of the correct size, heck even by some runtime magic messing with the underlying length on the array and getting a little block of memory back, obvious at great effort and cost given the implications for the generational memory allocator.<BR><BR>Garbage should be inaccessible to anything using reflection to be truly garbage. <BR><BR>What you describe is simply waste, or excess and is in no way different to the excess involved in List<T> or Dictionary<T> on free space allocated which is entirely wasted if you know you will never grow the collection anymore.<BR><BR>in a system with GC Garbage has specific meanings and you should avoid (ab)using the term for anything it is not.<BR><BR>[1] you can likely rely on it being exponential but this is an implementation detail<BR>[2] If you care you can avoid this by pre allocating the right amount or by calling sb.ToString(0,sb.Length)
 
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by ShuggyCoUk:<BR>Whilst this sounds like a useful thought process it is not, from the point of view of the runtime correct.<BR>As an example of existing behaviour with equivalent effect:<BR><BR>When using StringBuilder the algorithm for growing the backing array is to double[1] in size.<BR>When ToString is called on it it does not, by default strip off any excess length, it leaves them there avoiding an additional copy but possibly wasting a bit of space, a classic time/space trade off[2].<BR><BR>This excess is not garbage, to the GC, it is referenceable, and easily accessible by perfectly legal reflection. <BR>It could be *converted* into garbage by some code spotting such excess and swapping the underlying array away underneath it for one of the correct size, heck even by some runtime magic messing with the underlying length on the array and getting a little block of memory back, obvious at great effort and cost given the implications for the generational memory allocator. </div></BLOCKQUOTE><BR>I understand the difference between what I claimed was garbage and what the garbage collector sees as garbage. The garbage collector isn't smart enough to recognize every case where memory will never be used; if it were, it would be able to trim the character arrays (reflection discussed below). Nonetheless, I don't see a conceptual difference between the excess space in the character array and some object to which there are no references.<BR><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Garbage should be inaccessible to anything using reflection to be truly garbage. </div></BLOCKQUOTE><BR>And Java Strings are mutable and able to be sabotaged so operations on them fail unpredictably if you use reflection. I don't think that reckless use of reflection on core classes should in any way be supported by the platform. If the garbage collector were to automatically trim unused portions of strings' character arrays, some unsafe reflective code might fail with out of bounds exceptions and such, but who cares? Can you come up with a single rational situation in which one would want to reflectively access an unused portion of a string's character array? (Also consider that exactly when substrings reuse character arrays is unspecified, so such GC may simply be taking advantage of the freedom in the spec to determine when to reuse these arrays. Code relying on a particular implementation would be fundamentally flawed and the VM should physically ignite the computer on which it was written to stem the programmatic diarrhea flowing from it.)<BR><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">What you describe is simply waste, or excess and is in no way different to the excess involved in List<T> or Dictionary<T> on free space allocated which is entirely wasted if you know you will never grow the collection anymore. </div></BLOCKQUOTE><BR>That's not true in general because such space in a List or Dictionary could be accessed indirectly by adding elements via its public API. You'd have to analyze the context in which the List or Dictionary is used to determine whether that excess space will necessarily never be accessed.<BR><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">in a system with GC Garbage has specific meanings and you should avoid (ab)using the term for anything it is not. </div></BLOCKQUOTE><BR>I see the potential for confusion; perhaps it's unwise to use the word "garbage". However, it's clear that we both understand the difference between how I defined the term and what the GC collects.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">If the garbage collector were to automatically trim unused portions of strings' character arrays, some unsafe reflective code might fail with out of bounds exceptions and such, but who cares? </div></BLOCKQUOTE><BR><BR>This is fine, it's a well defined and controlled exception which never lets you out of the sandbox. <BR><BR>The problem is if someone takes a reference to a private (or public field) and then the runtime reallocates the memory to something else because it decided it was unreachable by your definition not mine. <BR><BR>Unless you rewrite the system to 'expire' references at considerable overhead of no utility in the common case you loose your nice sandbox. Someone can play memory hell with your code (and the regular behaviour of the GC memory allocator would make that a very real and exploitable problem)<BR><BR>Obviously when you can do unsafe (of java JNI) then this matters not a bit because, to quote a favourite of Raymond Chen's "It rather involved being on the other side of this airtight hatchway".<BR><BR>If you changed the way strings worked to not have a reference inside them, i.e. making the only way to get a 'reference' to the underlying memory via an inherently unsafe mechanism such as a pointer then you can start messing about with such mechanisms, you just have to make it invisible to existing mechanisms that know the internals of their implementation like the marshallers involved in P/Invoke/JNI etc.<BR><BR>In case you're thinking that reflection means you can mess with things to your hearts content anyway consider this. Even without it determining whether it is impossible for any code to cause access outside the bounds of the underlying array is rather a hard general problem. <BR>If the runtime writers screw that up then they have a bug, if they screw it up in your model they have a security exploit waiting to happen.<BR><BR>Given the pain of trying to replace things on the fly compared to the simplicity of the fix for the users who are affected by it why on earth would they try that approach.
 
I'm not saying that VMs <I>should</I> try to figure out and destroy referenced data that can never (reasonably) be used, as I realize that there are practical problems that the VM would have to contend with, such as the ones you mentioned. My point was simply that while there's a practical distinction between data that is unreachable because no pointer points to it and data that is unreachable because no code accesses it, namely that the former but not the latter is easily proven unreachable and therefore safe to GC, I see no meaningful inherent conceptual distinction between them, and therefore I consider both to be "garbage".
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">I see no meaningful inherent conceptual distinction between them, and therefore I consider both to be "garbage". </div></BLOCKQUOTE><BR><BR>Fair enough, I think the ability to provably and thus safely free the memory is worthy of some distinction but it's all just terminology after all.
 
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by LordHunter317:<BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Jackass JoeJoe:<BR>When you reference a string and it is replaced, what happens to other variables referencing the same string? </div></BLOCKQUOTE>If you could do that, the string isn't immutable. </div></BLOCKQUOTE><BR><BR>The point is to think of strings differently than references to objects. Once you see the expected behavior, then there's only one conclusion left: you need Copy for the "impossible" reason. For some odd reason someone needs the reference to not be equal. With my limited knowledge, I can't fathom the reason. Maybe it's related operator overloading, but string comparisons are optimized for reference comparisons internally.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Jackass JoeJoe:<BR>The point is to think of strings differently than references to objects. </div></BLOCKQUOTE>Huh? This literally makes no sense.<BR><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Once you see the expected behavior, then there's only one conclusion left: you need Copy for the "impossible" reason. </div></BLOCKQUOTE>No, as Meta quite clearly showed. Just because a type provides immutable semantics to its callers doesn't mean it's immutable internally.
 
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by newwb:<BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Metasyntactic:<BR>That's not a very good perspective to take though. The majority of classes and systems in the .Net work don't let you directly control anything. If your perspective on things is that that makes them garbage, then you'll find things rather difficult to deal with. </div></BLOCKQUOTE><BR>To me, garbage is data that your program will never be able to access (either directly or indirectly). <BR> </div></BLOCKQUOTE><BR>But who says you will never be able to access this data directly or indirectly?<BR><BR>For example, the String subsystem coudl be smart and could reuse portions of those arrays that it had determined were no longer in use. I've seen such systems before, though they are generally not used that much as it requires additional overhead to track what is/isn't in use (though it can be fantastic for areas where space saving is at a premium).<BR><BR>What's odd is that you think the runtime should meet *your* expectations on what waste is/isn't, versus what the author of the class you're using decided. I'm not sure why it should do that, or if that would be a good idea at all. Indeed, given the number of bad developers out there, who try to do all sorts of bad things with memory, i'm pretty sure it would be awful if the runtime went with what *you* think is wasted.<BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content"><BR>Suppose you create a string, substring it, then dereference the initial string, and the substring references the original character array. Then the portions of the character array that aren't part of the substring will never be accessible (at least without some major hackery, at which point all correctness bets are off), and therefore it is garbage. </div></BLOCKQUOTE>That's an implementation detail. You don't know if that's truly the case. I've worked with systems that can and do reuse such portions. And there's no reason the .Net system couldn't as well. That the current impl choses not to (i just checked) isn't really relevant. That's an implementation detail.
 
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Metasyntactic:<BR>But who says you will never be able to access this data directly or indirectly?<BR><BR>For example, the String subsystem coudl be smart and could reuse portions of those arrays that it had determined were no longer in use. I've seen such systems before, though they are generally not used that much as it requires additional overhead to track what is/isn't in use (though it can be fantastic for areas where space saving is at a premium). </div></BLOCKQUOTE><BR>My premise was that the data can't be accessed. If it can, it isn't garbage (by my definition). It seems like you think I'm making a declaration about all strings but I'm really just commenting about this particular implementation of strign.<BR><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">What's odd is that you think the runtime should meet *your* expectations on what waste is/isn't, versus what the author of the class you're using decided. I'm not sure why it should do that, or if that would be a good idea at all. Indeed, given the number of bad developers out there, who try to do all sorts of bad things with memory, i'm pretty sure it would be awful if the runtime went with what *you* think is wasted. </div></BLOCKQUOTE><BR>I didn't say anything about what the runtime should do (I even made that explicit here). Also, are you really arguing that data that can never be accessed but is stored in memory isn't waste? I realize that attempting to clean it up may be even more wasteful, but that's beside the point.<BR><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">That's an implementation detail. You don't know if that's truly the case. I've worked with systems that can and do reuse such portions. And there's no reason the .Net system couldn't as well. That the current impl choses not to (i just checked) isn't really relevant. That's an implementation detail. </div></BLOCKQUOTE><BR>Yes it's an implementation detail; I never said otherwise. My definition of what's garbage relies on implementation.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">but is stored in memory isn't waste? </div></BLOCKQUOTE><BR><BR>Actually it's not waste if you save effort by over allocationg.<BR><BR>Most simple container classes use exponential growth mechanisms to make insertion O(1) amortized cost.<BR><BR>It's a time/space trade off, and those that care can avoid the tradeoff (see previous posts)<BR><BR>There is already some fairly tight coupling of the runtime and strings/StringBuilders, making that even more complex would not be a good thing. Making sure *every* method in string never reads beyond the bounds of the notional memory capacity rather than the actual memory capacity would be a far more onerous check (with far worse results if you got it wrong).<BR><BR>If you choose to define 'Garbage' differently than the runtime provider that's fine* but you seem to think that it is automatically the case that such excess allocations are always either avoided or corrected for and I'm not seeing any justification for this view.<BR><BR>* Just expect to confuse other people and be called on it
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by DavlinLotze:<BR>So because of the way the string class is implemented, you can end up with the equivalent of uncollected garbage? </div></BLOCKQUOTE>Yes.<BR><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">So any time I'm using Substring() (or stuff like Split, Trim, etc.), I should consider the possible down-the-road memory benefit of enclosing it in string.Copy()? </div></BLOCKQUOTE>Doubtful, unless your strings are truly giant. <BR><BR><hr class="ev_code_hr" /><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Metasyntatic:<BR>No. Garbage should almost always be collected**. However, in the case i showed above, the char array is not garbage. It is being referenced, so it is rightfully kept around. </div></BLOCKQUOTE>Data that is no longer being used is garbage regardless of whether the GC considers it as such. Surely, if this weren't the case, String.Copy wouldn't even exist, right?<BR><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Not really no. You should do whatever is more natural and clear. </div></BLOCKQUOTE>Huh? There's nothing natural and clear about having to deal with a possible facet of the String class' implementation that's not even documented, yet still has an method call "just in case". Nor do I see how there ever can be.<BR><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Actually, it can very much be about efficiency. It's just about measuring efficiency in different ways. </div></BLOCKQUOTE>I'm not sure how one can "measure efficiency in different ways" here unless one changes the definition of efficiency.<BR><BR><hr class="ev_code_hr" /><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">ORiginally posted by ShuggyCoUk:<BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">therefore it is garbage. </div></BLOCKQUOTE>Whilst this sounds like a useful thought process it is not, from the point of view of the runtime correct. </div></BLOCKQUOTE>Sure, it is. Just because the runtime only collects unreachable garbage doesn't suddenly mean that only unreachable objects are garbage.<BR><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Garbage should be inaccessible to anything using reflection to be truly garbage. </div></BLOCKQUOTE>Accessing private members through the runtime lets you break a class, so I'm not sure it's of any concern. Certainly, if there were some way for the runtime to signal that you're the last reference to an object, then you'd have no objections to the String class shrinking its backing array at that point? If you don't, then the only logical conclusion is, "The unused part of the backing array is actually garbage". <BR><BR><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">The problem is if someone takes a reference to a private (or public field) and then the runtime reallocates the memory to something else because it decided it was unreachable by your definition not mine. </div></BLOCKQUOTE>No, there is no problem here. Either you end up with two objects, or one object in a different state. Neither lets you violate the runtime. Honestly, how can it be any other way?<BR><BR><hr class="ev_code_hr" /><BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by Metasyntatic:<BR>But who says you will never be able to access this data directly or indirectly?<BR><BR>For example, the String subsystem coudl be smart and could reuse portions of those arrays that it had determined were no longer in use. </div></BLOCKQUOTE>The those portions would still actually be in use, and ergo are not garbage. This isn't a hard concept. Again, just because the GC can't figure out doesn't change anything.<BR><BR>Let's be plain: if you didn't have a GC and it would be safe for you to delete it, then it's still garbage even if you have a GC, and even if the GC doesn't collect it. This certainly include things like the reserved space of an STL vector (which has the swap trick for a reason) or of a StringBuffer.
 
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by ShuggyCoUk:<BR>Actually it's not waste if you save effort by over allocationg.<BR><BR>Most simple container classes use exponential growth mechanisms to make insertion O(1) amortized cost.<BR><BR>It's a time/space trade off, and those that care can avoid the tradeoff (see previous posts) </div></BLOCKQUOTE><BR>In the case where collections over-allocate to leave room for growth, the extra space is not necessarily garbage (by my definition) from the point of view of the collection: the collection doesn't know whether more items will be added to it, and therefore whether it needs to use that extra space. Now, if you have a collection that you initialize, add 10 items to, and then provably never modify and the collection's internal capacity at that point is 16, the extra space is garbage. The ubiquitous ArrayList even lets you manually indicate that it should take that garbage to the curb: ArrayList.trimToSize().
 

Xavin

Ars Legatus Legionis
30,828
Subscriptor++
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by fitten:<BR>Be very, very, very, very, very, very, very careful here. </div></BLOCKQUOTE>This. Not only is a lot of optimization done prematurely, I find that when I do end up having performance issues, the cause is usually not what my first guess was. Optimizing for performance without profiling to be certain of exactly what the problem is just wastes time.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Data that is no longer being used is garbage regardless of whether the GC considers it as such. Surely, if this weren't the case, String.Copy wouldn't even exist, right? </div></BLOCKQUOTE><BR><BR>At this point you are arguing the semantics of the word, since the word isn't even my native language I will leave that one to others.<BR><BR>Plainly the data is, in the current implementation, excess. If that matters functions are available to the user to allow said excess to be removed (at some cost).<BR><BR>Avoiding creating the excess is trivial if you known the size in advance, dealing with it at a user level involves a reallocation and memory copy.<BR><BR>By taking your logic to the extreme any data which is technically reachable but the code guarantees it won't touch is garbage. Should the runtime try to deal with that too?<BR><BR>Barring arguments of the naming I really fail to see what you or newwb are actually arguing for? Plainly there is a distinction between areas of memory that a fixed cost, fully general algorithm can determine is/isn't reasonable to reuse and ones that cannot but that are in fact reusable. <BR><BR>Are you suggesting that tight coupling between standard types and the run time should be increased always? that it should be possible to change it depending on some mode? that the default should be to trim always? I don't get it, sorry if I'm being dense.
 

MilleniX

Ars Tribunus Angusticlavius
8,140
Subscriptor++
Shuggy: They're arguing about the definition of garbage. This isn't pointless semantics, though, because garbage is an actual technical term. Among researcher and pedants, any allocated bits that will not be accessed before deallocation or program termination are garbage. This is independent of the language and runtime environment even having garbage collection. Detecting all garbage is pretty easy to prove equivalent to building a halt-checker, though.<BR><BR>Garbage collector implementations need some (necessarily less than perfect) heuristic to detect and reclaim garbage. The reachability heuristic has been popular for a long time, such that many practitioners have it ingrained in them that if some block is reachable, it's not garbage. This is not correct, though. Consider the example of a (non-enumerable) dictionary data structure. As long as the dictionary object itself is reachable, all of the values within it are too. However, some key objects may cease to exist outside the dictionary itself, so that their corresponding value objects will never be accessed again*. Those value objects are garbage, no matter that there are pointers to them among live objects (those that will be referenced again).<BR><BR>If you're interested in reading some research on this, Melissa O'Neill and her students have written up papers on various aspects of this problem. This one might be most relevant to the current conversation.<BR><BR>Phil <BR><BR>* If you're going to make noise about someone else potentially still having a reference to those value objects, I'll note that I've done escape analysis and can prove that the dictionary holds the only pointer to them.
 
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by ShuggyCoUk:<BR>By taking your logic to the extreme any data which is technically reachable but the code guarantees it won't touch is garbage. Should the runtime try to deal with that too? </div></BLOCKQUOTE>Some in research try to argue exactly that. For example, it would be interesting to have a system that, because of program analysis, could determine that the following is waste and just elide it:<BR><BR><pre class="ip-ubbcode-code-pre">
static List<int> values = new List<int>()

...

while (true) {
values.Add(1);
}
</pre><BR><BR>Nothing reads from 'Values', so it actually be removed, and all references to it eliminated. Your code would behave the same, just that it would use far less memory.<BR><BR>Unfortunately, in a complicated system like .Net, waste like this is exceedingly difficult to practively remove. The very nature of the reflective system means that most types of analysis simply cannot know with any reasonable degree of certainty what may or may not be used. Similarly, the use of interfaces almost always rules out these sorts of optimizations as you really don't know what sorts of things may be happening under the covers when an interface call it made (for example .Add on an impl of IList could go mutate somethign else in the system). And, even if you know all the implementations of the interface at compile time, that doesn't help with when instances are dynamically constructed or loaded from some stream of bytes somewhere.<BR><BR>In very constrained languages, or if you constrain .Net enough, you might be able to do some of this. But, in practice, it's exceedingly useless. Far better to just provide diagnostics to the user to guide them toward making smart decisions about what can/can't be optimized away.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">In very constrained languages, or if you constrain .Net enough, you might be able to do some of this. But, in practice, it's exceedingly useless. </div></BLOCKQUOTE><BR><BR>Ah right, thanks Meta and MilleniX - If that was where they were going fine, it's an interesting topic.<BR><BR>I was writing under the (perhaps not well indicated) assumption we were talking about platforms like .Net/Java where introspection and dynamic runtime behaviour was entirely legal and expected.<BR><BR>Escape analysis is interesting since it adds another differentiator which can state with certainty that nothing outside its view can be referencing an object. But this is because the life cycle is constrained (essentially any reference passed off stack immediately means it's off reservation and can't be touched. <BR><BR>Is something garbage if it can be proved with certainty that it is/isn't legal to remove? or only proved to be definitely not garbage? If it requires knowledge not available to the runtime (but available to an external agent) is it still garbage in those terms?<BR><BR>For example is this garbage:<BR><BR><pre class="ip-ubbcode-code-pre">
var foo = new object();
Environment.FailFast();
Console.WriteLine(foo.ToString());
</pre><BR><BR>I know that foo can never be used. but is it garbage?
 
<BLOCKQUOTE class="ip-ubbcode-quote"><div class="ip-ubbcode-quote-title">quote:</div><div class="ip-ubbcode-quote-content">Originally posted by ShuggyCoUk:<BR>Is something garbage if it can be proved with certainty that it is/isn't legal to remove? or only proved to be definitely not garbage? If it requires knowledge not available to the runtime (but available to an external agent) is it still garbage in those terms?<BR><BR>For example is this garbage:<BR><BR><pre class="ip-ubbcode-code-pre">
var foo = new object();
Environment.FailFast();
Console.WriteLine(foo.ToString());
</pre><BR><BR>I know that foo can never be used. but is it garbage? </div></BLOCKQUOTE><BR>IMO, at a certain moment in time, a unit of memory is garbage iff from now on it can never be used. As has already been mentioned, it may be impossible in general for a turing machine to determine whether a unit of memory is garbage, but that's beside the point.
 

MilleniX

Ars Tribunus Angusticlavius
8,140
Subscriptor++
Metasyntactic":1utbw7hf said:
ShuggyCoUk":1utbw7hf said:
By taking your logic to the extreme any data which is technically reachable but the code guarantees it won't touch is garbage. Should the runtime try to deal with that too?
Some in research try to argue exactly that. For example, it would be interesting to have a system that, because of program analysis, could determine that the following is waste and just elide it:


static List<int> values = new List<int>()

...

while (true) {
values.Add(1);
}


Nothing reads from 'Values', so it actually be removed, and all references to it eliminated. Your code would behave the same, just that it would use far less memory.

So this just becomes
Code:
while(true) {
    // Do nothing
}
right? We can't change that it loops infinitely, just whether it makes the useless infinitely large list in the process?

Metasyntactic":1utbw7hf said:
Unfortunately, in a complicated system like .Net, waste like this is exceedingly difficult to practively remove. The very nature of the reflective system means that most types of analysis simply cannot know with any reasonable degree of certainty what may or may not be used. Similarly, the use of interfaces almost always rules out these sorts of optimizations as you really don't know what sorts of things may be happening under the covers when an interface call it made (for example .Add on an impl of IList could go mutate somethign else in the system). And, even if you know all the implementations of the interface at compile time, that doesn't help with when instances are dynamically constructed or loaded from some stream of bytes somewhere.

In very constrained languages, or if you constrain .Net enough, you might be able to do some of this. But, in practice, it's exceedingly useless. Far better to just provide diagnostics to the user to guide them toward making smart decisions about what can/can't be optimized away.
Funny thing about the analyses that go into this. For a long time, people assumed that very coarse analysis was not very much work, while better ones would be more, so they accepted pretty poor results. It turns out that more precise analysis leads to having less data to work on, so even if you've increased your exponents in a Big-O sense, you may be operating on only 1 element at each step, rather than a large set that leads to useless output. Once you do precise points-to and call-graph analysis (which actually go together in JVM/CLR sorts of environments, because of virtual method invocation), you can substitute implementations for interfaces, and get really useful results.

Phil
 
If reflection were only allowed on private members if they were annotated as "reflective", an analyzer could avoid having to care about reflection much of the time. In fact, pretty much all of the standard library's private members aren't meant to be reflectively accessed and therefore wouldn't be annotated, and as those are the most used classes, static analysis might actually be quite effective.

In the following code sample similar to the one that Meta posted, if the values variable is not annotated as reflective and is only assigned to once, and the implementation of list is specified at assignment, it would be easy to determine that the only method call on values, Add, only mutates the list. Because that method call's return value is not used, it can't possibly affect anything outside the list, so the values variable is safe to remove.

Code:
static IList<int> values = new List<int>();
static {
  values.Add(1);
}
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
so the values variable is safe to remove.

Sure but in isolation that's an entirely pointless optimization since the code removed was entirely pointless so trivial for a human to do too.

It's optimizations that are tricky for humans to do (or that would reduce in much less readable/maintainable code) that are where you want to spend the effort.

I'm prepared to believe such cases exist but no amount of trivial examples like that are going to convince people it's worthwhile.
 
MilleniX":ztks1mmr said:
Metasyntactic":ztks1mmr said:
ShuggyCoUk":ztks1mmr said:
By taking your logic to the extreme any data which is technically reachable but the code guarantees it won't touch is garbage. Should the runtime try to deal with that too?
Some in research try to argue exactly that. For example, it would be interesting to have a system that, because of program analysis, could determine that the following is waste and just elide it:


static List<int> values = new List<int>()

...

while (true) {
values.Add(1);
}


Nothing reads from 'Values', so it actually be removed, and all references to it eliminated. Your code would behave the same, just that it would use far less memory.

So this just becomes
Code:
while(true) {
    // Do nothing
}
right? We can't change that it loops infinitely, just whether it makes the useless infinitely large list in the process?
Sure. But you could also have a system that intelligently handles an infinite loop. For example, the runtime could realize that it would not make any further progress and stop scheduling it for the CPU. A very smart (non-.net) runtime could also just get rid of the thread entirely. It can't happen in .Net since threads are externally observable. i.e. it would change the semantics of the system since the thread wouldn't show up for another thread that expected it to be there.

There's also the issue (in .Net) that that loop can be exited. For example, if an async exception is injected into that thread while running.
Metasyntactic":ztks1mmr said:
Unfortunately, in a complicated system like .Net, waste like this is exceedingly difficult to practively remove. The very nature of the reflective system means that most types of analysis simply cannot know with any reasonable degree of certainty what may or may not be used. Similarly, the use of interfaces almost always rules out these sorts of optimizations as you really don't know what sorts of things may be happening under the covers when an interface call it made (for example .Add on an impl of IList could go mutate somethign else in the system). And, even if you know all the implementations of the interface at compile time, that doesn't help with when instances are dynamically constructed or loaded from some stream of bytes somewhere.

In very constrained languages, or if you constrain .Net enough, you might be able to do some of this. But, in practice, it's exceedingly useless. Far better to just provide diagnostics to the user to guide them toward making smart decisions about what can/can't be optimized away.
Funny thing about the analyses that go into this. For a long time, people assumed that very coarse analysis was not very much work, while better ones would be more, so they accepted pretty poor results. It turns out that more precise analysis leads to having less data to work on, so even if you've increased your exponents in a Big-O sense, you may be operating on only 1 element at each step, rather than a large set that leads to useless output. Once you do precise points-to and call-graph analysis (which actually go together in JVM/CLR sorts of environments, because of virtual method invocation), you can substitute implementations for interfaces, and get really useful results.

Phil
Sure. MSR is full of papers and implementations where this sort of thing happens. However, in practice you find that it's not actually that helpful. i.e. you get a few percent improvement in runtime at a huge cost in complexity as well as overhead on things like the JIT.

In practice better optimizations happen at the architectural level of your domain.
 
ShuggyCoUk":3sj18snk said:
Sure but in isolation that's an entirely pointless optimization since the code removed was entirely pointless so trivial for a human to do too.

It's optimizations that are tricky for humans to do (or that would reduce in much less readable/maintainable code) that are where you want to spend the effort.

I'm prepared to believe such cases exist but no amount of trivial examples like that are going to convince people it's worthwhile.
That example is trivial because it's an example. The general technique of finding isolated portions of a program to which data is written but from which data is never read, if applied to a large program, might find places where data could be optimized away by looking at complex usage patterns across many objects. Furthermore, it may be able to optimize in ways humans simply couldn't. For example, suppose a hash table maintains a length field returned by the size method but size() is never called on a particular hash table. The runtime could remove the length field and any updates to it for that particular instance but not for other hash tables.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Furthermore, it may be able to optimize in ways humans simply couldn't. For example, suppose a hash table maintains a length field returned by the size method but size() is never called on a particular hash table. The runtime could remove the length field and any updates to it for that particular instance but not for other hash tables..

But this is where a human *could* detect this and use an alternate interface implementation that didn't bother to maintain the size. The overhead to the runtime of trying to spot this sort of thing is immense, the bug surface is enormous and if it ever really maters the human can do it.

Again I'm not saying such complex structural rewriting is not a potential win (in limited form escape analysis has been shown to be very useful in java) but no-one here has shown any sort of compelling example at all, I invite you to do so...
 
ShuggyCoUk":36d6fzzt said:
But this is where a human *could* detect this and use an alternate interface implementation that didn't bother to maintain the size.
The human might not even know that the hash table maintains a size variable; the only noticeable effect would be performance. Furthermore, I'd rather not have to create a new class for every usage pattern. If the new hash table class were API-incompatible with the old, you could no longer pass that hash table to a method accepting another, or if the new hash table implements an O(n) size(), you'd have to remember to change back to the O(1) size() if someone calls size(). The burden of doing so would be immense.

The overhead to the runtime of trying to spot this sort of thing is immense, the bug surface is enormous and if it ever really maters the human can do it.
The optimizations could be done at compile time.
 
Status
Not open for further replies.