Skip to content

Commit 8b24cd1

Browse files
committed
[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
1 parent 7688fbc commit 8b24cd1

2 files changed

Lines changed: 26 additions & 5 deletions

File tree

src/changes/changes.xml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@
3838
<title>Release Notes</title>
3939
</properties>
4040
<body>
41+
<release version="1.3.1" date="2016-MM-DD" description="Feature and bug fix release">
42+
<action issue="CSV-181" type="update" dev="ggregory" due-to="Gary Gregory">Make CSVPrinter.print(Object) GC-free.</action>
43+
</release>
4144
<release version="1.3" date="2016-MM-DD" description="Feature and bug fix release">
4245
<action issue="CSV-179" type="add" dev="britter">Add shortcut method for using first record as header to CSVFormat</action>
4346
<action issue="CSV-180" type="add" dev="britter">Add withHeader(Class&lt;? extends Enum&gt;) to CSVFormat</action>

src/main/java/org/apache/commons/csv/CSVPrinter.java

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -121,15 +121,33 @@ public Appendable getOut() {
121121
*/
122122
public void print(final Object value) throws IOException {
123123
// null values are considered empty
124-
String strValue;
124+
// Only call CharSequence.toString() if you have to, helps GC-free use cases.
125+
CharSequence charSequence;
125126
if (value == null) {
126127
final String nullString = format.getNullString();
127-
strValue = nullString == null ? Constants.EMPTY : nullString;
128+
charSequence = nullString == null ? Constants.EMPTY : nullString;
128129
} else {
129-
strValue = value.toString();
130+
charSequence = value instanceof CharSequence ? (CharSequence) value : value.toString();
130131
}
131-
strValue = format.getTrim() ? strValue.trim() : strValue;
132-
this.print(value, strValue, 0, strValue.length());
132+
charSequence = format.getTrim() ? trim(charSequence) : charSequence;
133+
this.print(value, charSequence, 0, charSequence.length());
134+
}
135+
136+
private CharSequence trim(final CharSequence charSequence) {
137+
if (charSequence instanceof String) {
138+
return ((String) charSequence).trim();
139+
}
140+
final int count = charSequence.length();
141+
int len = count;
142+
int pos = 0;
143+
144+
while ((pos < len) && (charSequence.charAt(pos) <= ' ')) {
145+
pos++;
146+
}
147+
while ((pos < len) && (charSequence.charAt(len - 1) <= ' ')) {
148+
len--;
149+
}
150+
return (pos > 0) || (len < count) ? charSequence.subSequence(pos, len) : charSequence;
133151
}
134152

135153
private void print(final Object object, final CharSequence value, final int offset, final int len)

0 commit comments

Comments
 (0)