Java – why UUID Will the initial call to randomuuid () slow down?

Given the following code snippet, it generates a UUID Randomuuid(), I get the following performance results (in milliseconds):

public static void main(String[] args) {
    long tmp = System.currentTimeMillis();
    UUID.randomUUID();
    tmp = printDiff(tmp);
    UUID.randomUUID();
    tmp = printDiff(tmp);
    UUID.randomUUID();
    tmp = printDiff(tmp);
    UUID.randomUUID();
    tmp = printDiff(tmp);
}

private static long printDiff(final long prevIoUsTimestamp) {
    long tmp = System.currentTimeMillis();
    System.out.printf("%s%n",tmp - prevIoUsTimestamp);
    return tmp;
}

result:

971
6
0
0

JDK: 1.8 operating system: Windows 7

Why does only the initial call take so long? (nearly 1 second!)

Solution

This is the initialization of securerandom:

//from the source code of randomUUID
private static class Holder {
    static final SecureRandom numberGenerator = new SecureRandom();
}

But that's not all Those zeros should really jump in your face Therefore, the operation takes 0 ms; Does that mean they are less? Like a few nanoseconds or what did you do wrong?

There is an appropriate tool to measure these things, called jmh

@BenchmarkMode({ Mode.AverageTime,Mode.SingleShotTime })
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 2,time = 2,timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 2,timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class UUIDRandom {

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder().include(UUIDRandom.class.getSimpleName()).build();
        new Runner(opt).run();
    }

    @Benchmark
    @Fork(1)
    public UUID random() {
        return UUID.randomUUID();
    }
}

Output said:

Benchmark          Mode  Cnt  score   Error  Units
UUIDRandom.random  avgt    2  0.002          ms/op
UUIDRandom.random    ss    2  0.094          ms/op

In fact, the single shot time is far below the average

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>