Skip to content

Commit c5505ca

Browse files
committed
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 3bcc525 commit c5505ca

File tree

1 file changed

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

1 file changed

+12
-3
lines changed

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

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,10 @@
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;
30+
import java.util.Map;
2931
import java.util.Properties;
3032

3133
import org.springframework.lang.Nullable;
@@ -40,6 +42,7 @@
4042
* @author Rob Harrop
4143
* @author Dave Syer
4244
* @author Mahmoud Ben Hassine
45+
* @author Choi Wang Gyu
4346
*/
4447
public class DefaultFieldSet implements FieldSet {
4548

@@ -60,6 +63,8 @@ public class DefaultFieldSet implements FieldSet {
6063

6164
private List<String> names;
6265

66+
private Map<String, Integer> nameIndexMap;
67+
6368
/**
6469
* The {@link NumberFormat} to use for parsing numbers. If unset the {@link Locale#US}
6570
* will be used ('.' as decimal place).
@@ -137,6 +142,10 @@ public DefaultFieldSet(String[] tokens, String[] names, @Nullable DateFormat dat
137142
}
138143
this.tokens = tokens.clone();
139144
this.names = Arrays.asList(names);
145+
this.nameIndexMap = new HashMap<>(names.length);
146+
for (int i = 0; i < names.length; i++) {
147+
this.nameIndexMap.put(names[i], i);
148+
}
140149
setDateFormat(dateFormat == null ? getDefaultDateFormat() : dateFormat);
141150
setNumberFormat(numberFormat == null ? getDefaultNumberFormat() : numberFormat);
142151
}
@@ -450,11 +459,11 @@ protected String readAndTrim(int index) {
450459
* @throws IllegalArgumentException if a column with given name is not defined.
451460
*/
452461
protected int indexOf(String name) {
453-
if (names == null) {
462+
if (nameIndexMap == null) {
454463
throw new IllegalArgumentException("Cannot access columns by name without meta data");
455464
}
456-
int index = names.indexOf(name);
457-
if (index >= 0) {
465+
Integer index = nameIndexMap.get(name);
466+
if (index != null) {
458467
return index;
459468
}
460469
throw new IllegalArgumentException("Cannot access column [" + name + "] from " + names);

0 commit comments

Comments
 (0)