If you compare the performance of methods for which UnitRange has super-efficient implementations, this type will win hands down (note the use of interpolation of variables with $(...) when using macros from BenchmarkTools):julia> using BenchmarkToolsjulia> @btime sum($(1:1000_000)) 0.012 ns (0 allocations: 0 bytes)500000500000julia> @btime sum($(collect(1:1000_000))) 229.979 μs (0 allocations: 0 bytes)500000500000请记住,每次使用getindex访问元素时,UnitRange都会带来动态计算元素的成本.例如考虑以下功能:Remember that UnitRange comes with the cost of dynamically computing the elements every time you access them with getindex. Consider for example this function:function test(vec) sum = zero(eltype(vec)) for idx in eachindex(vec) sum += vec[idx] end return sumend让我们用UnitRange和普通的Vector对其进行基准测试:Let's benchmark it with a UnitRange and a plain Vector:julia> @btime test($(1:1000_000)) 812.673 μs (0 allocations: 0 bytes)500000500000julia> @btime test($(collect(1:1000_000))) 522.828 μs (0 allocations: 0 bytes)500000500000在这种情况下,调用普通数组的函数比使用UnitRange的函数要快,因为它不必动态计算100万个元素.In this case the function calling the plain array is faster than the one with a UnitRange because it doesn't have to dynamically compute 1 million elements.当然,在这些玩具示例中,遍历vec的所有元素而不是索引要更明智,但是在现实世界中,这种情况可能更明智.但是,最后一个示例表明,UnitRange不一定比普通数组更有效,尤其是在需要动态计算其所有元素的情况下.如果您可以利用可以在恒定时间内执行操作的专用方法(如sum),则UnitRange效率更高.Of course, in these toy examples it'd be more sensible to iterate over all elements of vec rather than its indices, but in real world cases a situation like these may be more sensible. This last example, however, shows that a UnitRange is not necessarily more efficient than a plain array, especially if you need to dynamically compute all of its elements. UnitRanges are more efficient when you can take advantage of specialised methods (like sum) for which the operation can be performed in constant time.作为文件备注,请注意,如果您最初有一个UnitRange,将其转换为普通的Vector以获得良好的性能不一定是一个好主意,特别是如果您只使用一次或转换为Vector的过程很少,涉及到范围所有元素的动态计算以及必要内存的分配:As a file remark, note that if you originally have a UnitRange it's not necessarily a good idea to convert it to a plain Vector to get good performance, especially if you're going to use it only once or very few times, as the conversion to Vector involves itself the dynamic computation of all elements of the range and the allocation of the necessary memory: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 这篇关于UnitRange和Array有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-07 06:57