I’m using JAXB, I need to know the length of generated XML, so I marshal the content to StringWriter, so which way is better to get the length:
aStringWriter.getBuffer().length();
or
aStringWriter.toString().length();
?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
EDIT: Calling
toString()will always create a new string… although it won’t need to copy the actual character data, just create a new string referring to the currentchar[]with the current length and count. CallinggetBuffer().length()doesn’t need to create any extra objects though, so it’s slightly more efficient.What are you doing with the output though? Aren’t you converting it to a string anyway?
Note that the length here will always be the length in characters though, so it won’t be suitable for something like the Content-Length header of an HTTP responses, which needs the value in bytes (i.e. after encoding).
EDIT: Okay, if you want the byte count instead, I suggest you create a
ByteArrayOutputStream, and either pass that directly to JAXB if you can (I’ve forgotten what the API looks like) or create anOutputStreamWriteraround it. That way you can get the binary length from theByteArrayOutputStreaminstead.