Include_string vs getfield

I used to use include_string to call a function with the name defined by the string. But it seems like a hack, doesn’t it? Now getfield appears more sensible, doesn’t it? But I don’t know what behind these two functions. Which is more efficient? Can anyone explain?

Why are you calling functions addressed by strings in a performance-sensitive context?

In various situations.

  1. I have a bunch of functions with the same signature, so I parse the script file and compile them into s String Array, and then run them one by one.

  2. I get DataFrame files which have the names of these functions.

Are there better ways doing these?

Could you be more specific? Why do you have a data file with a bunch of function names?

  1. in a file called myfunc.jl, I have the bunch of functions defined as:
function f1(x)
    such such ...
end

function f2(x)
    such such ...
end
....

This file is include the main script. But the main script also parses this file to compile all the function names into a array, then it calls them one by one.

  1. Some outputs including the function names are written in a csv data file for further analysis, where the function name are read in as String, by which the function is called upon.

I hope this clarifies.

So you want to dynamically call functions that are parsed from a file?

Some options that are likely much faster:

  • Make a Dict{String, Function}, put your functions in there and index with the string you parse from the file. You can make a macro that adds your function to the dictionary when it is declared, if that is convenient.
  • Just switch on the string, e.g.
    func = Symbol(readline(f))
    if line == :foo
        foo(a)
    elseif line == :bar
        bar(a)
    ...
    

include_string or getfield are not very useful for your purpose.

1 Like

Thanks for the tips.

When I make a Dict, don’t I have to do one of the following?

Dict("f1", include_string(Main, "f1"))
Dict("f1", getfield(Main, Symbol("f1")))

When you said " include_string or getfield are not very useful for your purpose", do you mean that they are very inefficient?

You do

Dict("f1" => Main.f1)