Kyle Carter
2 min readJul 19, 2022

--

This is a very reasonable thought but in this particular case doesn't hold. Since the original collection in this case is an ArrayList it is already backed by an array and indexes are done in constant time. In fact calling toArray() causes a defensive copy of the backing array to be made which may lead to a decrease in performance. It also forces us to stop using generics to their full ability. For completeness I did run the experiment again with the toArray and nonToArray versions. The top number in each set represents the nonToArray version and the bottom the toArray version:

#25

Benchmark Mode Cnt Score Error Units

TestSpeed.testManuallyOptimized thrpt 5 7633.983 38.000 ops/ms

Benchmark Mode Cnt Score Error Units

TestSpeed.testManuallyOptimized thrpt 5 7588.030 1141.480 ops/ms

#1000

Benchmark Mode Cnt Score Error Units

TestSpeed.testManuallyOptimized thrpt 5 193.597 4.990 ops/ms

Benchmark Mode Cnt Score Error Units

TestSpeed.testManuallyOptimized thrpt 5 187.950 50.445 ops/ms

#50000

Benchmark Mode Cnt Score Error Units

TestSpeed.testManuallyOptimized thrpt 5 2.323 0.864 ops/ms

Benchmark Mode Cnt Score Error Units

TestSpeed.testManuallyOptimized thrpt 5 2.577 0.486 ops/ms

#250000

Benchmark Mode Cnt Score Error Units

TestSpeed.testManuallyOptimized thrpt 5 0.437 0.026 ops/ms

Benchmark Mode Cnt Score Error Units

TestSpeed.testManuallyOptimized thrpt 5 0.437 0.151 ops/ms

The data makes me think that there is very little difference performance wise with these two solutions.

If however our original collection was a LinkedList or another data structure that didn't have constant time lookups your suggestion would be 100% correct.

Thanks for the comment, it caused me to think about our original collection which I hadn't actually given much thought which could have been bad.

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

No responses yet