Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does `@static` run?

@static expr is a way to only run expr once; for some sense of once.
but what sense of once is it?

Is it:

  • once per time the package is installed?
  • once per time the package is loaded?
  • some other definition

The most common use is for OS checking: e.g. ccall((@static Sys.iswindows() ? :_fopen : :fopen), ...)

I am wondering if I can use it to generate different code based on an environment variable: In particular JULIA_NUM_THREADS. This environment variable can change between runs of julia, but if it changes during the session nothing will react to it.

like image 776
Lyndon White Avatar asked Jan 04 '18 05:01

Lyndon White


People also ask

When static method is executed?

It executes whenever the class is loaded in memory. One class can have numerous static blocks, which will be executed in the same sequence in which they are written.

Do static methods run automatically?

A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically. The user has no control on when the static constructor is executed in the program. A static constructor is called automatically.

When should you see a static method?

Static methods are usually preferred when: All instance methods should share a specific piece of code (although you could still have an instance method for that). You want to call method without having to create an instance of that class. You must make sure that the utility class is never changed.

When would you use a static initialization block?

The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. Note: We use Initializer Block in Java if we want to execute a fragment of code for every object which is seen widely in enterprising industries in development.


1 Answers

It is run at parse time (technically it is run just after parse time, when macros are expanded). If used in a package with precompilation enabled (the default), then it will be evaluated the first time it is loaded (i.e. when you see the message "INFO: Precompiling module ...").

So no, you can't use it to generate different code based on environmental variables, unless you explicitly use __precompile__(false) outside the module (however then you will have longer loading times).

like image 150
Simon Byrne Avatar answered Sep 22 '22 23:09

Simon Byrne