Reputation: 96264
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 aNOP
?
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?
Upvotes: 5
Views: 406
Reputation: 9225
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
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.
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.
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
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
Upvotes: 4