ObjectIdSubclassMap: Micro-optimize wrapping at end of table

During a review of the class, Josh Bloch pointed out we can use
"i = (i + 1) & mask" to wrap around at the end of the table, instead
of a conditional with a branch.  This is generally faster due to one
less branch that will be mis-predicted by the CPU.

Change-Id: Ic88c00455ebc6adde9708563a6ad4d0377442bba
Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
This commit is contained in:
Shawn O. Pearce 2011-03-10 10:09:58 -08:00
parent 42f0b11153
commit d1e47df0da
1 changed files with 10 additions and 14 deletions

View File

@ -92,16 +92,15 @@ public void clear() {
* @return the instance mapped to toFind, or null if no mapping exists. * @return the instance mapped to toFind, or null if no mapping exists.
*/ */
public V get(final AnyObjectId toFind) { public V get(final AnyObjectId toFind) {
int i = toFind.w1 & mask; final int msk = mask;
int i = toFind.w1 & msk;
final V[] tbl = table; final V[] tbl = table;
final int end = tbl.length;
V obj; V obj;
while ((obj = tbl[i]) != null) { while ((obj = tbl[i]) != null) {
if (AnyObjectId.equals(obj, toFind)) if (AnyObjectId.equals(obj, toFind))
return obj; return obj;
if (++i == end) i = (i + 1) & msk;
i = 0;
} }
return null; return null;
} }
@ -157,16 +156,15 @@ public <Q extends V> void add(final Q newValue) {
* type of instance to store. * type of instance to store.
*/ */
public <Q extends V> V addIfAbsent(final Q newValue) { public <Q extends V> V addIfAbsent(final Q newValue) {
int i = newValue.w1 & mask; final int msk = mask;
int i = newValue.w1 & msk;
final V[] tbl = table; final V[] tbl = table;
final int end = tbl.length;
V obj; V obj;
while ((obj = tbl[i]) != null) { while ((obj = tbl[i]) != null) {
if (AnyObjectId.equals(obj, newValue)) if (AnyObjectId.equals(obj, newValue))
return obj; return obj;
if (++i == end) i = (i + 1) & msk;
i = 0;
} }
if (++size == grow) { if (++size == grow) {
@ -218,13 +216,11 @@ public void remove() {
} }
private void insert(final V newValue) { private void insert(final V newValue) {
int j = newValue.w1 & mask; final int msk = mask;
int j = newValue.w1 & msk;
final V[] tbl = table; final V[] tbl = table;
final int end = tbl.length; while (tbl[j] != null)
while (tbl[j] != null) { j = (j + 1) & msk;
if (++j == end)
j = 0;
}
tbl[j] = newValue; tbl[j] = newValue;
} }