我认为直接创建起来会更快,但是实际上,添加循环只需要一半的时间。发生了什么,放慢了这么多?
这是测试代码
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class Test_newArray {
private static int num = 10000;
private static int length = 10;
@Benchmark
public static int[][] newArray() {
return new int[num][length];
}
@Benchmark
public static int[][] newArray2() {
int[][] temps = new int[num][];
for (int i = 0; i < temps.length; i++) {
temps[i] = new int[length];
}
return temps;
}
}
Run Code Online (Sandbox Code Playgroud)
测试结果如下。
Benchmark Mode Cnt Score Error Units
Test_newArray.newArray avgt 25 289.254 ± 4.982 us/op
Test_newArray.newArray2 avgt 25 114.364 ± 1.446 …Run Code Online (Sandbox Code Playgroud) 有一个表和一个gin索引,插入1,000,000个随机数。0 < 数量 < 100,000。
测试两个等效查询
create table Test
(
id serial primary key,
code varchar(255) not null
);
create index Test_code_gin on Test using gin (code gin_trgm_ops);
-- Test1
explain analyse
select * from Test where code like '1234';
-- Test2
explain analyse
select * from Test where code = '1234';
Run Code Online (Sandbox Code Playgroud)
测试1使用gin_trgm_ops索引,执行时间:1.640 ms;
Test2不使用索引,执行时间:24.531 ms;
我该怎么做才能让 PostgreSQL 使用索引?或者修改ORM策略和我的SQL语句?或者干脆添加一个BTree索引?
听说Java支持“Loop Unswitching”,所以就在JMH上简单测试了一下。
我认为在 JIT 之后它们会完全相同。为什么是这样?
private final int TIMES = 1_000_000;
private boolean bool;
private Random r = new Random(93);
@Setup(Level.Invocation)
public void fresh() {
bool = r.nextBoolean();
}
@Benchmark
public void test1(Blackhole bh) {
for (int i = 0; i < TIMES; i++) {
if (bool) {
bh.consume(1);
} else {
bh.consume(2);
}
}
}
@Benchmark
public void test2(Blackhole bh) {
if (bool) {
for (int i = 0; i < TIMES; i++) {
bh.consume(1);
}
} else { …Run Code Online (Sandbox Code Playgroud)