Block comments in Julia: #= vs """

Viewed 241

I know that block comments in Julia is officially #= ... =#. I also know that multiline strings are """ ... """.

However, I have seen a lot of source codes use """ ... """ on the top of the file to write documentation, and Julia seems to interpret this as a comment (for instance: Flux.jl).

My question is: if I use """ ... """ for any type of lengthy, multiline comments (e.g. describing function parameters), would there be any type of downside over using #= ... =#? I would like to know any performance penalties, potential side effects during parsing, etc... Why would one use #= over """, other than personal preference?

2 Answers

""" in front of the function are docstrings that are later seen by Julia's help system (e.g. when you type ?funnctionname or can be used for automated documentation generation that is usually integrated into CI processes with tools such as Travis).

To understand what is going on, try this simple Julia session:

julia> """
           myfoo(bar::AbstractVector)
       Returns the length of `bar`
       """
       myfoo(bar::AbstractVector) = length(bar)
myfoo

help?> myfoo
search: myfoo

  myfoo(bar::AbstractVector)

  Returns the length of bar

julia>

Julia does read the triple quotes as strings, not as comments. String Basics

Julia also allows you to write a documentation for some function, that you write on top of the function. This can be simple or triple quoted. Triple quotes are usually used, because they are more useful for longer blocks of text. Documentation

Julia enables package developers and users to document functions, types and other objects easily via a built-in documentation system. The basic syntax is simple: any string appearing at the toplevel right before an object (function, macro, type or instance) will be interpreted as documenting it (these are called docstrings). Note that no blank lines or comments may intervene between a docstring and the documented object.

You asked for performance penalties. You can try this with:

julia> using BenchmarkTools

julia> @btime """Hello
       Hello
       Hello"""
  1.694 ns (0 allocations: 0 bytes)
"Hello\nHello\nHello"

julia> @btime #=Hello
       Hello
       Hello=#1
  0.020 ns (0 allocations: 0 bytes)

(I need to put anything after the comment, because the syntax would not be correct otherwise)

So you see, parsing a String takes 1.6ns, while the comment does not take any time at all. However, docstrings are only parsed once when the package is loaded, while executing some function, they do not count. So except if you have a script something like this

for i in 1:10^10
   include("file_with_docstring.jl")
end

the parsing time for the docstring will not have any influence at all in the code. So the best way to go is by standard practice and write comments with # or #= [...] =# and docstrings using simple or triple quotes " [...] ", """ [...] """.

Related