LinkedList 和 ArrayDeque的性能分析( 三 )

Now previous method could be simplified. We just need to get a new ListIterator in case when required element is not present in the list.
public static void cleanStringListFast( final LinkedList\u0026lt;String\u0026gt; lst, final String first ){ ListIterator\u0026lt;String\u0026gt; iter = findElem( lst, first ); if ( !iter.hasNext() ) //if element is not present - process the full list\u0026lt; iter = lst.listIterator(); while ( iter.hasNext() ) { if ( iter.next().length() == 5 ) iter.remove(); }} So, as a rule, do not use any LinkedList methods which accept or return the position of an element in the list. Especially, do not try old style iteration:
final List\u0026lt;Integer\u0026gt; lst = new LinkedList\u0026lt;Integer\u0026gt;();for ( int i = 0; i \u0026lt; 100000; ++i ) lst.add( i );long sum = 0;for ( int i = 0; i \u0026lt; 100000; ++i ) sum += lst.get( i ); This code takes unexpected 6 seconds to complete! Do not even try to iterate a LinkedListcontaining a million elements this way. You\u0026#39;ll get tired waiting. The only exception to this rule is accessing/removing first or last element of the list (or one of the few first/last elements).
removeFirst/pollFirstWhile working with LinkedList, keep in mind that it is not a simple List, but a Deque. Rather often in code using LinkedList I see the following construct:
public T next(){ if ( lst.isEmpty() ) return null; return lst.removeFirst();} LinkedList.removeFirst() (as well as LinkedList.remove()) returns first element if the list is not empty or throws NoSuchElementException if the list is empty. This exception is the common reason why removeFirst is guarded is isEmpty call.
Such code is excessive, because LinkedList provides pollFirst method which does exactly the same as above mentioned next method - returns null if the list is empty otherwise the first element. So, right method can save one check and make the code more clear in this case. The same is applicable to removeLast/pollLast pair.
Batch processingSometimes you may have a LinkedList which contains some data obtained from the several sources and you need to process data from each source separately. For example, you have a real time network event log ordered by event timestamps. Each element of this log has, for example, IP address property, which specifies network device (computer, router, etc.) where this event has happened. You need to process events related to each IP address separately. Besides, you can\u0026#39;t collect information for the long time and process IP addresses separately - it is a real time log, so we can\u0026#39;t afford to delay processing for too long (either we have to response to some events not later than N seconds after these events or we have a large network, so it would take too much memory to keep/process all events at once).


推荐阅读