What are the recommended best practices for and common pitfalls of using Compile? [duplicate]

As evidenced in my last question there is much I do not know about how to write compilable functions.

The basics are clear: one must load the appropriate packages

Needs["CCompilerDriver"]
Needs["CompiledFunctionTools"]


and should check the availability of a suitable compiler:

CCompilers[Full]


and it is helpful to remind oneself of the functions that can be used that avoid MainEvaluate (for which I had not recorded the source but am now happy to credit to this thread where there is also other useful information)

CompileCompilerFunctions[] // Sort
InternalCompileValues[];(*to trigger \
syms = DownValues[InternalCompileValues] /.
HoldPattern[
Verbatim[HoldPattern][InternalCompileValues[sym_]] :> _] :> sym;
Complement[syms, CompileCompilerFunctions[]]


But, once all that is done must still remember that a compiled function definition expects its arguments to be of well-defined kinds - Integer, Real, Complex and n-dimensional tensors (matrices).

What is unclear, even after re-reading documentation, is the proper specification and use of temporary variables. It appears, for example, that these too must be of simple types and that the compiler does not automatically coerce them to compatible types. Then too there is the question of using e.g. GetElement even thought Part is a compilable function, and why Do may be better than Table.

Where can such additional information be found and what guidance would the community offer re writing functions for compilation?

marked as duplicate by C. E., MarcoB, m_goldberg, Henrik Schumacher, Alex TrounevApr 1 at 12:06

• "It appears, for example, that these too must be of simple types [...]". Of course. How else should it be possible to generate native C code? GetElement is faster than Part but also more fragile: If not used carefulle, it may cause a kernel crash (because, e.g., the operating system detects that Mathematica tries to access memory that it is not to allowed to have access to.). Table has to allocate memory for the output while Do does not. So Do` is faster if no output is to be generated. – Henrik Schumacher Mar 30 at 12:26