I'm trying to improve my code's performance, and I've found an area where the execution time is being significantly increased. I've had a look through the code but I can't see how I can improve it.
AddData
gets called over 200,000 times.
public void AddData(String label, int fromid, int toid, double distance, boolean oneway, int speedlimit)
{
currentRoad = new Edge(label, fromid, toid, distance, speedlimit, oneway);
tempVertex = allVertices.GetValue(fromid);
tempVertex.addEdge(currentRoad);
allEdges.AddItem(currentRoad);
if (!oneway)
{
currentRoad = new Edge(label, toid, fromid, distance, speedlimit, oneway);
tempVertex = allVertices.GetValue(toid);
tempVertex.addEdge(currentRoad);
}
}
The method within the AddData
function that takes a large proportion of the time is allEdges.AddItem()
.
allEdges
is a Hash Map containing vectors of Edges. (Edges is a class).
Here is my implementation of the Hash Map AddItem
function:
public void AddItem(Edge value)
{
if ((noofitems/data.length) > 0.7)
{
long time = System.nanoTime();
EdgeHashPair[] newMap = new EdgeHashPair[data.length * multiplier];
multiplier = 8;
for (EdgeHashPair oldMap1 : data)
{
if (oldMap1 != null)
{
int index = HashFunction(oldMap1.data.GetItem(0).label);
int increment = 1;
index = index % newMap.length;
boolean inserted = false;
while (!inserted)
{
if (newMap[index] == null)
{
newMap[index] = oldMap1;
inserted = true;
}
else
{
index = index + (increment<<1);
index = index % newMap.length;
}
}
}
}
data = newMap;
System.out.println("Hash map resizing took: " + ((System.nanoTime() - time)/1000000) + "ms");
}
int index=HashFunction(value.label);
index = index % data.length;
int increment = 1;
boolean inserted = false;
while (!inserted)
{
if (data[index] == null)
{
data[index] = new EdgeHashPair();
data[index].addItem(value);
noofitems++;
inserted = true;
}
else
{
if (data[index].data.GetItem(0).label.compareTo(value.label) == 0)
{
data[index].addItem(value);
inserted = true;
noitems++;
}
else
{
index = index + (increment<<1);
index = index % data.length;
}
}
}
}
Hash function:
private int HashFunction(String key)
{
// Task 1 code: Hash the key and return a long value
int code = 29;
for (int i=0; i < key.length(); i++)
{
code = code*53+(key.charAt(i));
}
return (code < 0 ? -code : code);
}
From timings I've done, the loading of data currently takes around 50% of my execution time (around 1000ms), which I feel is extremely high and would love to be able to reduce this.
Edit: The program is a navigation application, it stores edges and vertices and then calculates many routes.
java.util.HashMap
shouldn't be used. – maaartinus Apr 28 at 15:42