Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Performance and measurement in Java

Performance and measurement in Java: Java performance depends first on algorithmic complexity and data structures, then on allocation, locality, synchronization, GC, and JIT optimization.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

performance

Java performance depends first on algorithmic complexity and data structures, then on allocation, locality, synchronization, GC, and JIT optimization.

Profile a representative workload first, choose collections for the dominant operations, and measure elapsed time as a difference of System.nanoTime values rather than wall-clock time.

A single cold measurement is distorted by JIT compilation, dead-code elimination, and GC; a hand-written microbenchmark may measure code unlike production.

The origin of nanoTime is arbitrary and only differences are meaningful; parallelism can slow a small task, and a better asymptotic algorithm wins only beyond a relevant input size.

For target 31 the counters yield linear=32 versus binary=6, while elapsed-nonnegative=true demonstrates a System.nanoTime difference without machine-dependent timing output.

Examples

public class Main {
    static int linearComparisons(int[] values, int target) {
        int comparisons = 0;
        for (int value : values) {
            comparisons++;
            if (value == target) break;
        }
        return comparisons;
    }

    static int binaryComparisons(int[] values, int target) {
        int low = 0, high = values.length - 1, comparisons = 0;
        while (low <= high) {
            int middle = (low + high) >>> 1;
            comparisons++;
            if (values[middle] == target) break;
            if (values[middle] < target) low = middle + 1;
            else high = middle - 1;
        }
        return comparisons;
    }

    public static void main(String[] args) {
        int[] values = new int[32];
        for (int i = 0; i < values.length; i++) values[i] = i;
        System.out.println("linear=" + linearComparisons(values, 31));
        System.out.println("binary=" + binaryComparisons(values, 31));
        long started = System.nanoTime();
        long elapsed = System.nanoTime() - started;
        System.out.println("elapsed-nonnegative=" + (elapsed >= 0));
    }
}

Result

linear=32
binary=6
elapsed-nonnegative=true

For target 31 the counters yield linear=32 versus binary=6, while elapsed-nonnegative=true demonstrates a System.nanoTime difference without machine-dependent timing output.

Sources