简体   繁体   中英

Efficient usage of TextWriter

Is there any alternative way to perform the operation:

textWriter.Write(myBigObject.ToString())

such that:

  • myBigObject is 'streamed' into the text representation without creating the whole string object in memory
  • there are no additional classes or objects used, beside myBigObject and textWriter

Example: Imagine that myBigObject has 50 string fields. There is no point in joining all these fields in a big string and then writing the object to a file, if it is somehow possible to write the strings one by one to the file.

If you have access to the code, you can add a method to MyBigObject that takes a TextWriter and writes out each property. For example:

public class MyBigObject
{
    public void Write(TextWriter writer)
    {
        writer.Write(bigStringField1);
        writer.Write(bigStringField2);
        // etc.
    }
}

If sub-classes of MyBigObject need to write their own representation, then make the method virtual, and the sub-classes call the implementation in the base class.

If you don't own the code, and the fields are exposed through properties, you could build an adapter class that takes a MyBigObject and writes out each property. You could also build some extension methods that do the same thing.

If you cannot access the source code, you could use reflection to do examine the fields on the object, grab the value of each field, and Write() out each value's ToString() representation. However, reflection is slower than direct field access, and it involves a lot more intermediate objects. I don't know if using reflection would be worth it in your case.

Given the limitations you have outlined this isn't possible. You would have to come up with a way to read the data from your object and write it out on char/byte/line at a time.

If you want to be able to loop over your properties and write them out one at a time then this would be possible using reflection . However I suspect going this route would result in using more memory than your original solution as well as being much more complicated than a simple call to .ToString().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM