GistTree.Com
Entertainment at it's peak. The news is by your side.

The missing harm of manual dispatch in Julia

0

Correct a snappy one this day:
New customers of Julia coming from other dynamically typed languages could perchance perchance furthermore write capabilities fancy

characteristic foo(x)
    if x isa Int
        x + x
    elseif x isa Drift64
        x / 2.0
    elseif x isa String
        length(x)
    else
        1
    pause
pause

Right here is clearly unidiomatic and could perchance perchance be written as

bar(x:: Int) = x + x
bar(x:: Drift64) = x / 2.0
bar(x:: String) = length(x)
bar(x) = 1 # or bar(x::Any), to be explicit

because it’s nicer to read and certainly easy to prolong for other types of x.
Effectively, you technically can prolong foo the same scheme as bar, but reading the definition of foo one would seek recordsdata from to then know its full habits, so it’d be deceptive.

Nonetheless, my point is that there could be de facto (perhaps surprisingly) no damage at runtime for code as in foo!
The Julia compiler isn’t tricked that with out bother and will still assemble optimal machine code for each and every kind of the argument:

julia> @code_native debuginfo=: none bar(1)
    .text
    leaq	(%rdi,%rdi), %rax
    retq
    nopw	%cs: (%rax,%rax)

julia> @code_native debuginfo=: none foo(1)
    .text
    leaq	(%rdi,%rdi), %rax
    retq
    nopw	%cs: (%rax,%rax)

Every capabilities generally collect all of the diagram down to a single adding instruction (leaq; retq is for getting back from the characteristic and nopw is an operation that does nothing and is there for technical reasons).
Judge about it this scheme:
When Julia compiles foo(1), it knows that 1 is of sort Int, can assume in regards to the x isa Int expression at collect time to obedient, and discard all the pieces however the x + x with out an self-discipline.

“Appendix”

For completeness, right here is what’s produced in the opposite circumstances:

julia> @code_native debuginfo=: none bar(1.0)
    .text
    movabsq	$140581530607976, %rax  # imm = 0x7FDBB031A168
    vmulsd	(%rax), %xmm0, %xmm0
    retq
    nop

julia> @code_native debuginfo=: none foo(1.0)
    .text
    movabsq	$140581530608088, %rax  # imm = 0x7FDBB031A1D8
    vmulsd	(%rax), %xmm0, %xmm0
    retq
    nop


julia> @code_native debuginfo=: none bar("abc")
    .text
    pushq	%rax
    movabsq	$"ncodeunits;", %rax
    callq	*%rax
    popq	%rcx
    retq
    nop

julia> @code_native debuginfo=: none foo("abc")
    .text
    pushq	%rax
    movabsq	$"ncodeunits;", %rax
    callq	*%rax
    popq	%rcx
    retq
    nop


julia> @code_native debuginfo=: none bar([])
    .text
    movl	$1, %eax
    retq
    nopw	%cs: (%rax,%rax)

julia> @code_native debuginfo=: none foo([])
    .text
    movl	$1, %eax
    retq
    nopw	%cs: (%rax,%rax)

Read More

Leave A Reply

Your email address will not be published.