# `UnitRange` 和 `Array` 有什么区别？

#### What is the difference between `UnitRange` and `Array`?

``````sum = 0
for x in 1:100
sum += x
end
``````
``````sum = 0
for x in collect(1:100)
sum += x
end
``````

2 个回复

`UnitRange`将使用常量空间，而`Array`将与您正在迭代的元素数量成比例地增长。

``````julia> @btime sum(1:1000000)
0.044 ns (0 allocations: 0 bytes)
500000500000

julia> @btime sum(collect(1:1000000))
1.123 ms (2 allocations: 7.63 MiB)
500000500000
``````

``````julia> dump(1:100)
UnitRange{Int64}
start: Int64 1
stop: Int64 100
``````

``````function getindex(v::UnitRange{T}, i::Integer) where {T<:OverflowSafe}
@_inline_meta
val = v.start + (i - 1)
@boundscheck _in_unit_range(v, val, i) || throw_boundserror(v, i)
val % T
end
``````

``````function sum(r::AbstractRange{<:Real})
l = length(r)
# note that a little care is required to avoid overflow in l*(l-1)/2
return l * first(r) + (iseven(l) ? (step(r) * (l-1)) * (l>>1)
: (step(r) * l) * ((l-1)>>1))
end
``````

``````julia> using BenchmarkTools

julia> @btime sum(\$(1:1000_000))
0.012 ns (0 allocations: 0 bytes)
500000500000

julia> @btime sum(\$(collect(1:1000_000)))
229.979 μs (0 allocations: 0 bytes)
500000500000
``````

``````function test(vec)
sum = zero(eltype(vec))
for idx in eachindex(vec)
sum += vec[idx]
end
return sum
end
``````

``````julia> @btime test(\$(1:1000_000))
812.673 μs (0 allocations: 0 bytes)
500000500000

julia> @btime test(\$(collect(1:1000_000)))
522.828 μs (0 allocations: 0 bytes)
500000500000
``````

``````julia> @btime collect(\$(1:1000_000));
422.435 μs (2 allocations: 7.63 MiB)

julia> @btime test(collect(\$(1:1000_000)))
882.866 μs (2 allocations: 7.63 MiB)
500000500000
``````
1 Julia中的UnitRange类型是什么意思？

2018-08-13 21:13:06 1 457   julia
2 Array和Array（）有什么区别？

4 数组和列表有什么区别

2016-10-13 21:35:05 2 1673   swift
5 malloc和array有什么区别

2016-03-31 00:08:24 2 81   malloc
6 切片和数组之间有什么区别？

8 JSON 和 Array 有什么区别？

JSON 和 Array 有什么区别？ 他们为什么称 JSON 对象和数组对象。 http://wiki.appcelerator.org/display/guides/Using+TableViews+-+data.js 这是一个数组还是 JSON？ 我如何识别？ ...

9 生成器和数组有什么区别？

10 ArrayBuffer和Array有什么区别

2015-07-03 20:19:06 4 7304   scala