One reason would be to reduce pressure on the compiler: this will perform 
badly in terms of memory usage and compilation time because a separate 
version of "f" has to be compiled for every "T":

immutable X{T}
  val::T
end

f(x) = println("got $(x.val)")

for i=1:10^5
  f(X((zeros(i)...)))
end


On Wednesday, October 28, 2015 at 10:58:57 AM UTC-4, Cedric St-Jean wrote:
>
> On Wednesday, October 28, 2015 at 8:10:41 AM UTC-4, Stefan Karpinski wrote:
>>
>> The key behavioral difference between these two is that with the 
>> non-parametric union version you can change both the value and the type of 
>> the field of a MyType object after construction, whereas in the parametric 
>> version you can change the value of the field after an object has been 
>> constructed, but not the type – since the object is either a MyType{Int} or 
>> a MyType{Float64}.
>>
>
> Given that reasoning, is there any reason to have an immutable with fields 
> that have abstract/unspecified types? Isn't it always better to use a 
> parametric type?
>
>  
>
>>
>> On Wed, Oct 28, 2015 at 3:21 AM, Gnimuc Key <[email protected]> wrote:
>>
>>> that makes sense. many thanks!
>>>
>>> 在 2015年10月28日星期三 UTC+8下午3:14:26,Tomas Lycken写道:
>>>
>>>> With a type declared like that, any access of the field x will be type 
>>>> unstable, which means that Julia’s JIT compiler will emit much more 
>>>> defensive, and thus slower, code.
>>>>
>>>> The solution is to declare a *parametric* type:
>>>>
>>>> type MyType{T<:Union{Int64, Float64}}
>>>>     x::T
>>>> end
>>>>
>>>> That way, MyType(3) and MyType(3.0) will now be instances of different 
>>>> types, and the compiler can generate fast code. (You can still write 
>>>> functions that dispatch on just MyType, so you don’t loose any 
>>>> expressive power…)
>>>>
>>>> // T
>>>>
>>>> On Wednesday, October 28, 2015 at 5:10:09 AM UTC+1, Gnimuc Key wrote:
>>>>
>>>> Avoid type Unions in fields ¶
>>>>>>
>>>>>> <http://docs.julialang.org/en/latest/manual/style-guide/#avoid-strange-type-unions>
>>>>>> type MyType
>>>>>> ...
>>>>>> x::Union{Void,T}
>>>>>> end
>>>>>
>>>>>  
>>>>> I'm wondering whether it's a good style or not to write something like 
>>>>> this:
>>>>>
>>>>> type MyType
>>>>>     ...
>>>>>     x::Union{Int64,Float64}end
>>>>>
>>>>> what's the side effects of using Union like this?
>>>>>
>>>> ​
>>>>
>>>
>>

Reply via email to