5

I recently asked the following question about Python: Interpreter optimization in Python

Say I have a string in x, is the Python interpreter smart enough to know that: string.replace(x, x) should be converted to a NOP?

The answer seems to be No (although the Python interpreter is able to do some optimizations through the peephole optimiser).

I don't know what the equivalent expression in Julia would be, but is Julia capable of optimizing these types of relatively obvious statements?

1
  • 1
    I think the answer is "sometimes", in that it will propagate constants and eliminate dead code. Its hard to answer without a more specific case as it can be very difficult to infer for the compiler in some cases (although its probably easier than in Python) Commented Aug 11, 2014 at 22:01

1 Answer 1

4

Relying on the compiler

The question is can Julia provide enough information to LLVM so that the compiler can optimize things?

From your example yes, and you can verify with code_native. For example the answer is premultiplied and unnecessary assignment to x is optimized away and the function always returns a constant

julia> f()=(x=7*24*60*60)
f (generic function with 1 method)

julia> code_native(f,())
    .section    __TEXT,__text,regular,pure_instructions
Filename: none
Source line: 1
    push RBP
    mov  RBP, RSP
    mov  EAX, 604800
Source line: 1
    pop RBP
    ret

Optimization from typing

And it can go a bit further at times because more knowledge is available from type information. The converse is that the Any type and globals are to be avoided if possible.

Example

In case I, the comparison needs to be made because y might be greater than 256, but in the 2nd case since it's only 1 byte, it's value can't be greater than 256 and the function will be optimized to always return 1.

Case I

julia> g(y::Int16)=(y<256?1:0)
g (generic function with 1 method)

julia> code_native(g,(Int16,))
    .section    __TEXT,__text,regular,pure_instructions
Filename: none
Source line: 1
    push RBP
    mov  RBP, RSP
    cmp  DI, 256
Source line: 1 
    setl  AL
    movzx EAX, AL
    pop   RBP
    ret

Case II

julia> g(y::Int8)=(y<256?1:0)
g (generic function with 2 methods)

julia> code_native(g,(Int8,))
    .section    __TEXT,__text,regular,pure_instructions
Filename: none
    Source line: 1
    push RBP
    mov  RBP, RSP
    mov  EAX, 1
Source line: 1
    pop  RBP
    ret
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.