单例数组的魔力从何而来? [英] Where does the magic of singleton arrays come from?

查看:36
本文介绍了单例数组的魔力从何而来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Vector{Missing}Vector{Int} 之间的以下区别让我感到惊讶(以积极的方式):

The following difference between Vector{Missing} and Vector{Int} surprised me (in a positive way):

julia> @btime fill(20, 10^7);
  15.980 ms (2 allocations: 76.29 MiB)

julia> @btime fill(missing, 10^7);
  20.603 ns (1 allocation: 80 bytes)

julia> Base.summarysize(fill(20, 10^7))
80000040

julia> Base.summarysize(fill(missing, 10^7))
40

julia> typeof(fill(20, 10^7))
Vector{Int64} (alias for Array{Int64, 1})

julia> typeof(fill(missing, 10^7))
Vector{Missing} (alias for Array{Missing, 1})

鉴于 fill(missing, n) 不会产生像 FillArray,这个对单例的优化是如何实现的?我想它会以某种方式自动从单例大小为零的事实中消失,但是如何呢?

Given that fill(missing, n) does not result in some optimized structure like FillArray, how is this optimization on singletons implemented? I guess it falls out in some way automagically from the fact that singletons have zero size, but how?

我试图阅读 array.cjulia.h,但不能真正关注细节.也许真正的问题是 运行时系统如何处理单例...?

I tried to read array.c and julia.h, but can't really follow the details enough. Maybe the real question is instead how are singletons handled by the runtime system...?

推荐答案

基本答案是对于 a = Array(T) Julia 总是分配 sizeof(T)*length(a)+40 字节.由于 sizeof(Missing) == 0,这意味着它不会分配任何与长度相关的字节.

The basic answer is that for an a = Array(T) Julia always allocates sizeof(T)*length(a)+40 bytes. Since sizeof(Missing) == 0, this means it doesn't allocate any bytes related to the length.

索引发生在 array 的 第 569 行.c,相关行是

Indexing occurs on line 569 of array.c, and the relevant line is

jl_value_t *r = undefref_check((jl_datatype_t*)eltype, jl_new_bits(eltype, &((char*)a->data)[i * a->elsize]))

当数组大小为零时,a->data[i * a->elsize]a->data的开头.然而,它的内容是完全不相关的:当 eltype 为零 jl_datatype_size 时,jl_new_bits 忽略数据指针,而是返回 instance 字段>eltype,也就是单例对象.

When the size of the array is zero, a->data[i * a->elsize] refers to the beginning of a->data. The content of this is, however, completely irrelevant: when eltype has zero jl_datatype_size, jl_new_bits ignores the data pointer and instead returns the instance field from the eltype, which is the singleton object.

这篇关于单例数组的魔力从何而来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆