[CSV-181] Make CSVPrinter.print(Object) GC-free.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/csv/trunk@1742895 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Gary D. Gregory 2016-05-09 08:49:57 +00:00
parent 7688fbc3f9
commit 8b24cd1fb0
2 changed files with 26 additions and 5 deletions

View File

@ -38,6 +38,9 @@
<title>Release Notes</title>
</properties>
<body>
<release version="1.3.1" date="2016-MM-DD" description="Feature and bug fix release">
<action issue="CSV-181" type="update" dev="ggregory" due-to="Gary Gregory">Make CSVPrinter.print(Object) GC-free.</action>
</release>
<release version="1.3" date="2016-MM-DD" description="Feature and bug fix release">
<action issue="CSV-179" type="add" dev="britter">Add shortcut method for using first record as header to CSVFormat</action>
<action issue="CSV-180" type="add" dev="britter">Add withHeader(Class&lt;? extends Enum&gt;) to CSVFormat</action>

View File

@ -121,15 +121,33 @@ public final class CSVPrinter implements Flushable, Closeable {
*/
public void print(final Object value) throws IOException {
// null values are considered empty
String strValue;
// Only call CharSequence.toString() if you have to, helps GC-free use cases.
CharSequence charSequence;
if (value == null) {
final String nullString = format.getNullString();
strValue = nullString == null ? Constants.EMPTY : nullString;
charSequence = nullString == null ? Constants.EMPTY : nullString;
} else {
strValue = value.toString();
charSequence = value instanceof CharSequence ? (CharSequence) value : value.toString();
}
strValue = format.getTrim() ? strValue.trim() : strValue;
this.print(value, strValue, 0, strValue.length());
charSequence = format.getTrim() ? trim(charSequence) : charSequence;
this.print(value, charSequence, 0, charSequence.length());
}
private CharSequence trim(final CharSequence charSequence) {
if (charSequence instanceof String) {
return ((String) charSequence).trim();
}
final int count = charSequence.length();
int len = count;
int pos = 0;
while ((pos < len) && (charSequence.charAt(pos) <= ' ')) {
pos++;
}
while ((pos < len) && (charSequence.charAt(len - 1) <= ' ')) {
len--;
}
return (pos > 0) || (len < count) ? charSequence.subSequence(pos, len) : charSequence;
}
private void print(final Object object, final CharSequence value, final int offset, final int len)