Should I use `Code.ensure_loaded?/1`?

I saw a commit in Ecto: Avoid expensive Code.ensure_loaded/1 checks · elixir-ecto/ecto@46674c3 · GitHub

Which seems to avoid using Code.ensure_loaded?/1, I had used this function to check the module availability. So should I use try instead?

1 Like

I think that’s just because the function in question is potentially called often, and the check happens at runtime. ensure_loaded requires a synchronous call to the code server so it’s rather slow. I would still prefer it in code that’s not too performance-critical.

1 Like

Ensure_loaded is great if you can get away with doing it only once, like at code-gen time. ^.^

3 Likes

During runtime, I make use of the Code.ensure_loaded?/1 function and call it for every loop that I have. each loop of my macro is extended by 800 nanoseconds as a result of this.
The use of the try command did not yield any results, it is equal with Code.ensure_loaded?/1 .

How would you recommend a function to check whether or not a module has been loaded? a function that is contained within a loop or within a function that is not for compile time

I have deleted all Code.ensure_loaded?/1 from runtime,

with Code.ensure_loaded?/1 my project took 67 millisecond after deleting it takes less than 300 microsecond. do not use this in runtime, especially when you have a loop

Very useful note.

My work:

  1. move some re-checks to compile time
  2. change my structure
  3. check some place with function_exported?
  4. use try instead of. it is not recommended