-
Enhancement
-
Resolution: Not an Issue
-
P5
-
None
-
1.4.1
-
generic
-
generic
LinkedList.indexOf could take advantage of the fact that "header" entry has a null element for increased performance when it is passed a null "target":
public int indexOf(Object o) {
int index = 0;
if (o==null) {
// header.element guaranteed null, no chance of looping past header
for (Entry e = header.next; e.element != null; e = e.next) {
index++;
}
// if index < size, null was found, else we looped to header
return (index < size) ? index: -1;
} else {
for (Entry e = header.next; e != header; e = e.next) {
if (o.equals(e.element))
return index;
index++;
}
}
return -1;
}
Applying a similar transformation to lastIndexOf yields very pretty results:
public int lastIndexOf(Object o) {
int index = size - 1;
if (o==null) {
for (Entry e = header.previous; e.element != null;
e = e.previous, index--);
} else {
for (Entry e = header.previous; e != header && !o.equals(e.element);
e = e.previous, index--);
}
return index;
}
public int indexOf(Object o) {
int index = 0;
if (o==null) {
// header.element guaranteed null, no chance of looping past header
for (Entry e = header.next; e.element != null; e = e.next) {
index++;
}
// if index < size, null was found, else we looped to header
return (index < size) ? index: -1;
} else {
for (Entry e = header.next; e != header; e = e.next) {
if (o.equals(e.element))
return index;
index++;
}
}
return -1;
}
Applying a similar transformation to lastIndexOf yields very pretty results:
public int lastIndexOf(Object o) {
int index = size - 1;
if (o==null) {
for (Entry e = header.previous; e.element != null;
e = e.previous, index--);
} else {
for (Entry e = header.previous; e != header && !o.equals(e.element);
e = e.previous, index--);
}
return index;
}
- relates to
-
JDK-6897553 LinkedList performance improvements
-
- Resolved
-