相关疑难解决方法(0)

奇怪的JIT对循环习语的悲观化

在分析最近一个问题的结果时,我遇到了一个非常奇怪的现象:显然,HotSpot的额外一层JIT优化实际上会降低我机器上的执行速度.

这是我用于测量的代码:

@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
@OperationsPerInvocation(Measure.ARRAY_SIZE)
@Warmup(iterations = 2, time = 1)
@Measurement(iterations = 5, time = 1)
@State(Scope.Thread)
@Threads(1)
@Fork(2)
public class Measure
{
  public static final int ARRAY_SIZE = 1024;
  private final int[] array = new int[ARRAY_SIZE];

  @Setup public void setup() {
    final Random random = new Random();
    for (int i = 0; i < ARRAY_SIZE; ++i) {
      final int x = random.nextInt();
      array[i] = x == 0? 1 : x;
    }
  }

  @GenerateMicroBenchmark public int normalIndex() …
Run Code Online (Sandbox Code Playgroud)

java cpu intel microbenchmark jmh

18
推荐指数
1
解决办法
338
查看次数

为什么"新"关键字比赋值更有效?

我有两种方法可以读取字符串,并创建Character对象:

static void newChar(String string) {
    int len = string.length();
    System.out.println("Reading " + len + " characters");
    for (int i = 0; i < len; i++) {
        Character cur = new Character(string.charAt(i));

    }       
}
Run Code Online (Sandbox Code Playgroud)

static void justChar(String string) {
    int len = string.length();
    for (int i = 0; i < len; i++) {
        Character cur = string.charAt(i);

    }
}
Run Code Online (Sandbox Code Playgroud)

当我使用18,554,760字符串运行方法时,我的运行时间差异很大.我得到的输出是:

newChar took: 20 ms
justChar took: 41 ms
Run Code Online (Sandbox Code Playgroud)

对于较小的输入(4,638,690个字符),时间不会变化.

newChar took: 12 ms
justChar took: 13 ms
Run Code Online (Sandbox Code Playgroud)

在这种情况下,为什么新的效率更高?

编辑: …

java performance new-operator

13
推荐指数
2
解决办法
704
查看次数

使用自己的int容量比使用数组的.length字段更快?

马丁·汤普森"95%的表现是关于清洁的代表性模型"谈话中,在17到21分钟之间,这样的代码被呈现:

public class Queue
{
    private final Object[] buffer;
    private final int capacity;

    // Rest of the code

}
Run Code Online (Sandbox Code Playgroud)

在20:16他说:

你可以获得更好的性能,所以留下像这样的东西capacity 是正确的.

我试图提出一个代码示例,其capacity速度会快得多buffer.length,但我失败了.

马丁说两个场景中出现问题:

  1. 在一个并发的世界里.但是,length字段也是final,JLS 10.7.所以,我不知道这可能是一个什么问题.
  2. 当缓存未命中时.试着打电话capacityVS buffer.length一百万次(具有元素一百万队列),但没有显著差异.我使用JMH进行基准测试.

能否请您提供一个代码示例,该示例演示了一个capacity优于buffer.length性能的案例?

更常见的情况(经常在实际代码中发现)越好.

请注意,我完全取消了美学,清洁代码,代码重新分解等方面的内容.我只询问性能.

java concurrency performance caching

11
推荐指数
1
解决办法
248
查看次数