Skip to content
This repository has been archived by the owner on Oct 26, 2019. It is now read-only.

Research Java Speed of Operations

Harrison Leach edited this page Aug 12, 2019 · 1 revision

Use for loops instead of streams [1]

Streams are 10 - 30% slower than using a simple for loop. For example:

int sumOfEarliestTimes = Arrays.stream(aStarSchedule.getEarliestTimes()).sum();

Should be replaced with:

int sumOfEarliestTimes = 0;

for(int time : aStarSchedule.getEarliestTimes()) {
    sumOfEarliestTimes += time;
}

While streams can be parallelised, we don't want to introduce this just yet as it could interfere with our future multithreading plans.

Check the current log level first [2]

If creating a debug or info log in a performance-critical area of code (e.g. a piece of code frequently used by the a-star algorithm) check the log level before invoking a logger.

For example:

logger.debug("node 1 cost: " + node1.processingCost() + "node 2 cost:" + node2.processingCost());

Should be replaced with:

if(logger..isDebugEnabled()) {
   logger.debug("node 1 cost: " + node1.processingCost() + "node 2 cost:" + node2.processingCost());
}

This is because even though it may not be logged, the string will still be concatenated. It is most likely better if debug logs are left out of performance-critical code anyway.

Use StringBuilder/Buffer if creating strings in loops [2]

Similar to above, if creating a debug or info log in a performance-critical area of code avoid performing concatenation operation of strings like below:

String debug = "Nodes in graph: ";
for (INode node : graph.getNodes()) {
    debug += node.getLabel();
}

This is because a new String object must be created for each concatenation. Instead, use a StringBuilder/Buffer as below.

StringBuilder builder = new StringBuilder("Nodes in graph: ");
for (INode node : graph.getNodes()) {
    builder.append(node.getLabel());
}

References

[1] https://raygun.com/blog/java-performance-optimization-tips/

[2] https://stackify.com/java-performance-tuning/