-3

I have 2 codes tbat do same thing. I am wondering which one will be faster:

1.

import org.apache.commons.collections.CollectionUtils;
String [] htArray = StringUtils.join (CollectionUtils.subtract (
    Arrays.asList ((h + " " + t).split (" ") ),
    Arrays.asList (htSelected.split (" ") ) ), " " ).split (" ");
for (String term: htArray ) {
    ...
}

2.

import org.apache.commons.collections.CollectionUtils;
ArrayList <String> htList = null;
try {
    htList = (ArrayList <String>) CollectionUtils.subtract (
        Arrays.asList ( (h + " " + t).split (" ") ), 
        Arrays.asList (htSelected.split (" ") ) );
} catch (Exception except) {}

if ( htList != null) {
    for (String term: htList) {
        ...
    }
}

The 1st one joins a collection then splits the string into an array. The second one casts the collection, does try/catch then adds an 'if'. Which one is optimal?

user unknown
  • 35,537
  • 11
  • 75
  • 121
Mugoma J. Okomba
  • 3,185
  • 1
  • 26
  • 37
  • 6
    I am sure that in writing out this question that in a similar timeframe, that you could have tested this out for yourself. – Valamas Apr 25 '12 at 22:32
  • The question was not about timeframe parse but about both timeframe & elegance. If we forget about timeframe, which of the logic makes sense? The join/split looks almost ridiculous (why join a list and split it?) and is the method I used before a colleague pointed that out to me. On the hand hand the 2nd method forces one to write many lines of code just to achieve same result. – Mugoma J. Okomba Apr 26 '12 at 05:42
  • I quote "I am wondering which one will be faster:" – Valamas Apr 26 '12 at 05:44

1 Answers1

1

Run it 100 times and figure out

bluish
  • 26,356
  • 27
  • 122
  • 180
Tasawer Khan
  • 5,994
  • 7
  • 46
  • 69
  • 2
    or 100000 and use currentTimeMillis to view the elapsed times. – Vladimir Apr 25 '12 at 22:34
  • 1
    This won't work. You need to be really careful how you benchmark java to make sure you're measuring the right thing -- steady state performance after class load and JIT optimization with the same VM settings as production code. See http://www.ibm.com/developerworks/java/library/j-benchmark1/index.html for an explanation of Java benchmarking pitfalls. – Mike Samuel Apr 25 '12 at 22:36
  • 2
    @Vladimir, `System.nanoTime` is better than `currentTimeMillis` which is not guaranteed to be [monotonic](http://stackoverflow.com/a/2979239/20394). – Mike Samuel Apr 25 '12 at 22:36
  • You shouldn't trust results which depend on nanoTime, because it is to small, to easily influenced by other processes. It should at least run for some seconds, so that you get differences in the range of 1s (or not). – user unknown Apr 26 '12 at 12:50