The best way to see what's going on is with the code_llvm and code_native
functions. For example, here's a case of a function defined to use
zero(ModInt{11}):

julia> include("examples/modint.jl")
showcompact (generic function with 9 methods)

julia> f() = zero(ModInt{11})
f (generic function with 1 method)

julia> code_llvm(f,())

define %ModInt @julia_f15196() {
top:
  ret %ModInt zeroinitializer, !dbg !389
}

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


As you can see "caching" is not really a sensible thing to talk about here.
If we were creating a value and retrieving it from memory, that would be
entirely too slow. Instead, the compiler knows that the representation of a
ModInt is just a natively sized integer and it knows how to construct a
zero-valued one efficiently.

What you're suggesting is memoization, which has come up a number of times.
The short version is that it is an easy way to speed up a slow language but
is worse than useless in fast languages. You don't see people doing
memoization in C or Fortran, do you? If the result of some computation is
expensive, you may want to cache it explicitly, but you'll want to do that
with a globally constant, typed cache inside of the function definition.
Ideally, using an array, not a hash.


On Tue, Feb 25, 2014 at 6:59 AM, andrew cooke <[email protected]> wrote:

> To what extent does the system cache / reuse immutable instances?
>
> For example, I have a zero(...) function that returns zero for a
> particular (immutable) numeric type.  Do I need to cache that myself, or
> will the system somehow intern values and re-use the same instance?
>
> Bonus question - is there a macro(?) that can be applied to a function and
> which automatically adds LRU caching of the result by argument with weak
> references?
>
> Thanks,
> Andrew
>
>

Reply via email to