很多时候需要逐个扫描Array中数据,并根据计算规则计算数据。
这里以对比数据为例给出两种计算方式:
1 使用内置函数all 过滤array
test_1(x) = all(y->y==x[1],x)
2 这里有一个 自定义 函数,它使用了内联函数。效率明显提高了。
@inline function test_2(x)
length(x) < 2 && return true
e1 = x[1]
i = 2
@inbounds for i=2:length(x)
x[i] == e1 || return false
end
return true
end
代码效率对比,明显第2种方式比较好
using BenchmarkTools
v = fill(1,10_000_000);
test_1(v)
test_2(v)
@btime test_1($v);
# 14.616 ms (0 allocations: 0 bytes)
@btime test_2($v);
#11.080 ms (0 allocations: 0 bytes)
v[100] = 2
@btime test_1($v);
#85.944 ns (0 allocations: 0 bytes)
@btime test_2($v);
#63.761 ns (0 allocations: 0 bytes)