谁是最好得UUID生成算法

原创
2022/06/22 22:13
阅读数 104

UUID经常用来作为唯一键得生成算法被普遍使用,然而,高并发下,UUID的性能会下降非常快。这是依赖于UUID的种子输入以及算法,下面程序可以验证UUID的性能

import com.github.f4b6a3.uuid.UuidCreator;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 2)
@Measurement(iterations = 2, time = 5, timeUnit = TimeUnit.SECONDS)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
@Threads(100)
@Fork(1)
public class UUIDTest {



  @Benchmark
  public UUID uuidDefault(){
    return UUID.randomUUID();
  }

  @Benchmark

  @Fork(value=1,jvmArgsAppend="-Djava.security.egd=file:/dev/urandom")
  public UUID uuidNonblockRandom(){
    return UUID.randomUUID();
  }

  @Benchmark
  @Fork(value=1,jvmArgsAppend="-Djava.security.egd=file:/dev/random")
  public UUID uuidBlockRandom(){
    return UUID.randomUUID();
  }


  @Benchmark
  @Fork(value=1,jvmArgsAppend="-Djava.security.egd=file:/dev/./urandom")
  public UUID uuidNonblockRandom_2(){
    return UUID.randomUUID();
  }

  @Benchmark
  @Fork(value=1)
  public UUID timeBasedUUID(){
    return  UuidCreator.getTimeBased();
  }



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

maven 文件

 <properties>
        <jmh.version>1.35</jmh.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.openjdk.jmh</groupId>
            <artifactId>jmh-core</artifactId>
            <version>${jmh.version}</version>
        </dependency>
        <dependency>
            <groupId>org.openjdk.jmh</groupId>
            <artifactId>jmh-generator-annprocess</artifactId>
            <version>${jmh.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.github.f4b6a3</groupId>
            <artifactId>uuid-creator</artifactId>
            <version>4.6.1</version>
        </dependency>
    </dependencies>

在一个8C服务器上,200并发测试

Benchmark                         Mode  Cnt       Score   Error  Units
TestPerUUID.timeBasedUUID         avgt    2   12121.222          ns/op
TestPerUUID.uuidBlockRandom       avgt    2  171027.253          ns/op
TestPerUUID.uuidDefault           avgt    2  186085.858          ns/op
TestPerUUID.uuidNonblockRandom    avgt    2  238918.598          ns/op
TestPerUUID.uuidNonblockRandom_2  avgt    2   60984.722          ns/op
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部