> Can you comment on the performance implications of directly accessing 
> fields vs your approach?  I'm guessing that directly accessing the fields 
> would be faster?

I think usually it should get inlined and there is no difference:

julia> immutable A
       a::Int
       end

julia> function f1(a::A,n)
       out = 0
       for i=1:n
       out += a.a
       end
       end

f1 (generic function with 1 method)

julia> getA(a::A) = a.a
getA (generic function with 1 method)

julia> function f2(a::A,n)
       out = 0
       for i=1:n
       out += getA(a)
       end
       end
f2 (generic function with 1 method)

julia> @code_native f1(A(5),10)
        .text
Filename: none
Source line: 4
        pushq   %rbp
        movq    %rsp, %rbp
Source line: 4
        popq    %rbp
        ret

julia> @code_native f2(A(5),10)
        .text
Filename: none
Source line: 4
        pushq   %rbp
        movq    %rsp, %rbp
Source line: 4
        popq    %rbp
        ret

>
>> On Wednesday, April 08, 2015 06:35:46 AM Kristoffer Carlsson wrote: 
>> > I come from a Python background where direct access to fields in for 
>> > example classes with the dot notation is very common. 
>> > 
>> > However, from what I have seen in different conversations, accessing 
>> fields 
>> > directly is not really Julian. Sort of a "fields are an implementation 
>> > detail" mindset, and "what is important are the functions". 
>> > 
>> > Here is an example of a type hierarchy that is a little bit similar to 
>> > types I am working with now: 
>> > 
>> > type Element 
>> >     vertices::Vector{Int} 
>> > end 
>> > 
>> > type Node 
>> >     coordinates::Vector{Float64} 
>> >     id::Int 
>> > end 
>> > 
>> > type FESection 
>> >     elements::Vector{Elements} 
>> >     nodes::Vector{Nodes} 
>> > end 
>> > 
>> > type Mesh 
>> >    sections::Vector{FESection} 
>> > end 
>> > 
>> > Now, let's say that I want to write a function to loop over all 
>> vertices. 
>> > One way (which I would do in Python is): 
>> > 
>> > mesh = Mesh(.....) 
>> > for section in mesh.sections 
>> >     for element in section.elements 
>> >         for vertices in element.vertices 
>> >               blah bla 
>> >         end 
>> >     end 
>> > end 
>> > 
>> > 
>> > 
>> > However, this accesses the fields directly. Would it be more Julian to 
>> > write getters for the fields? Since Julia does not have @property like 
>> > Python I realize that by accessing the fields you commit to exactly the 
>> > name of the field and it's type while with a getter it would be more 
>> > flexible. 
>> > 
>> > Best regards, 
>> > Kristoffer Carlsson 
>>
>>

Reply via email to