I came across this (Java) code yesterday and can't figure out why someone would have done this in any language.
In what scenario, language, paranoid delusion would "removing" values from an ArrayList like this improve performance? Try to avoid getting dragged in to the general design of the worker. I know it's bad and should be different, but I'm trying to understand if there is a reason for writing a 'remove' method this way.
Some points of clarification:
- tradeIdList contains no duplicate values
- It is populated in the constructor and never read until the worker has finished.
The class reading this result simply prints the contents to a log file.
public class TradeIdWorker implements Runnable{ private List tradeIdList = new ArrayList(); ....
public void run(){ // Copy the tradeIdList to an array (No I do not know why) for (int tradeId : tradeIdArray){ .... // Once processed, remove it removeProcessedTradeId(tradeId); } /** * Set Trade id to zero (for performance) */ private void removeProcessedTradeId(int tradeId) { for (int index = 0; index < tradeIdList.size(); index++) { if (tradeIdList.get(index).intValue() == tradeId) { tradeIdList.set(index, 0); } } }
To try and understand why I've added a real world use case from the system. The arraylist of tradeIds never contains duplicates.
public static void main(String[] args) {
testNormalRemove();
testPerformantRemove();
}
private static void testNormalRemove() {
ArrayList<Integer> aList = new ArrayList<Integer>();
for (int i = 0; i < 1000000; i++) {
aList.add(i);
}
long start = System.currentTimeMillis();
for (int i = 0; i < aList.size(); i += 1000) {
aList.remove((Object) i);
}
long end = System.currentTimeMillis();
System.out.println("Normal Took: " + (end - start)); // 1700ms
}
private static void testPerformantRemove() {
ArrayList<Integer> aList = new ArrayList<Integer>();
for (int i = 0; i < 1000000; i++) {
aList.add(i);
}
long start = System.currentTimeMillis();
for (int i = 0; i < aList.size(); i += 1000) {
for (int index = 0; index < aList.size(); index++) {
if (aList.get(index).intValue() == i) {
aList.set(index, 0);
}
}
}
long end = System.currentTimeMillis();
System.out.println("Performant Took: " + (end - start)); // 4800ms
}