Skip to content

Commit 480a343

Browse files
cwangg897fmbenhassine
authored andcommitted
Improve indexOf() performance in DefaultFieldSet
Replaced linear List#indexOf with a precomputed Map-based index lookup This reduces the time complexity from O(n) to O(1), improving performance for field lookups in wide CSV files. This change preserves existing behavior and error messages Resolves: #4930 Signed-off-by: Choi Wang Gyu <dhkdrb897@gmail.com>
1 parent 82bd3a2 commit 480a343

File tree

1 file changed

+12
-3
lines changed
  • spring-batch-infrastructure/src/main/java/org/springframework/batch/infrastructure/item/file/transform

1 file changed

+12
-3
lines changed

spring-batch-infrastructure/src/main/java/org/springframework/batch/infrastructure/item/file/transform/DefaultFieldSet.java

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,11 @@
2424
import java.text.SimpleDateFormat;
2525
import java.util.Arrays;
2626
import java.util.Date;
27+
import java.util.HashMap;
2728
import java.util.List;
2829
import java.util.Locale;
2930
import java.util.Objects;
31+
import java.util.Map;
3032
import java.util.Properties;
3133

3234
import org.springframework.util.Assert;
@@ -43,6 +45,7 @@
4345
* @author Dave Syer
4446
* @author Mahmoud Ben Hassine
4547
* @author Stefano Cordio
48+
* @author Choi Wang Gyu
4649
*/
4750
public class DefaultFieldSet implements FieldSet {
4851

@@ -63,6 +66,8 @@ public class DefaultFieldSet implements FieldSet {
6366

6467
private @Nullable List<String> names;
6568

69+
private @Nullable Map<String, Integer> nameIndexMap;
70+
6671
/**
6772
* Create a FieldSet with anonymous tokens.
6873
* <p>
@@ -124,6 +129,10 @@ public DefaultFieldSet(@Nullable String[] tokens, String[] names, @Nullable Date
124129
}
125130
this.tokens = tokens.clone();
126131
this.names = Arrays.asList(names);
132+
this.nameIndexMap = new HashMap<>(names.length);
133+
for (int i = 0; i < names.length; i++) {
134+
this.nameIndexMap.put(names[i], i);
135+
}
127136
this.dateFormat = dateFormat != null ? dateFormat : getDefaultDateFormat();
128137
setNumberFormat(numberFormat != null ? numberFormat : getDefaultNumberFormat());
129138
}
@@ -446,11 +455,11 @@ public int getFieldCount() {
446455
* @throws IllegalArgumentException if a column with given name is not defined.
447456
*/
448457
protected int indexOf(String name) {
449-
if (names == null) {
458+
if (nameIndexMap == null) {
450459
throw new IllegalArgumentException("Cannot access columns by name without meta data");
451460
}
452-
int index = names.indexOf(name);
453-
if (index >= 0) {
461+
Integer index = nameIndexMap.get(name);
462+
if (index != null) {
454463
return index;
455464
}
456465
throw new IllegalArgumentException("Cannot access column [" + name + "] from " + names);

0 commit comments

Comments
 (0)