Skip to content

Commit b8a0e07

Browse files
committed
Make it faster
1 parent 696edc4 commit b8a0e07

File tree

2 files changed

+671
-153
lines changed

2 files changed

+671
-153
lines changed
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
/*
2+
* Copyright 2024 java-diff-utils.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.github.difflib.algorithm.myers;
17+
18+
/**
19+
* A simple open-addressing hash map for int -> int mappings.
20+
* Avoids boxing overhead of HashMap<Integer, Integer>.
21+
*/
22+
final class IntIntMap {
23+
private int[] keys;
24+
private int[] values;
25+
private boolean[] allocated;
26+
private int size;
27+
private int capacity;
28+
private int threshold;
29+
30+
IntIntMap(int initialCapacity) {
31+
capacity = 1;
32+
while (capacity < initialCapacity) {
33+
capacity = capacity << 1;
34+
}
35+
keys = new int[capacity];
36+
values = new int[capacity];
37+
allocated = new boolean[capacity];
38+
threshold = (int) (capacity * 0.75);
39+
}
40+
41+
void put(int key, int value) {
42+
if (size >= threshold) {
43+
resize();
44+
}
45+
46+
int idx = findInsertIndex(key);
47+
if (!allocated[idx]) {
48+
allocated[idx] = true;
49+
keys[idx] = key;
50+
size++;
51+
}
52+
values[idx] = value;
53+
}
54+
55+
int get(int key) {
56+
int idx = findIndex(key);
57+
if (idx == -1) {
58+
return 0; // default value
59+
}
60+
return values[idx];
61+
}
62+
63+
private int findIndex(int key) {
64+
int idx = key & (capacity - 1);
65+
while (allocated[idx]) {
66+
if (keys[idx] == key) {
67+
return idx;
68+
}
69+
idx = (idx + 1) & (capacity - 1);
70+
}
71+
return -1;
72+
}
73+
74+
private int findInsertIndex(int key) {
75+
int idx = key & (capacity - 1);
76+
while (allocated[idx]) {
77+
if (keys[idx] == key) {
78+
return idx;
79+
}
80+
idx = (idx + 1) & (capacity - 1);
81+
}
82+
return idx;
83+
}
84+
85+
private void resize() {
86+
int[] oldKeys = keys;
87+
int[] oldValues = values;
88+
boolean[] oldAllocated = allocated;
89+
int oldCapacity = capacity;
90+
91+
capacity = capacity << 1;
92+
threshold = (int) (capacity * 0.75);
93+
keys = new int[capacity];
94+
values = new int[capacity];
95+
allocated = new boolean[capacity];
96+
size = 0;
97+
98+
for (int i = 0; i < oldCapacity; i++) {
99+
if (oldAllocated[i]) {
100+
put(oldKeys[i], oldValues[i]);
101+
}
102+
}
103+
}
104+
}

0 commit comments

Comments
 (0)