Based on your sample code, it looks like you want to time something, then print out the elapsed time with a caption, is that correct? If so, I would advice a slightly different approach. First, performance is not something I would worry about at all. That print statement is likely to be thousands of times slower than accessing the time variable. Rather, the problems I see with the current approach are:
- Method directly modifies external data.
- Print statements separated, what if there’s other IO output in between, or you have multiple timers and happen to mix up captions and timers?
- Variable name
t is so short that comments are needed to explain what it is.
- The single-element-vector idiom to achieve mutability, although fairly common in many languages, is often considered a hack, typically needs comments explaining what’s going on, and even then always attracts the wrong kind of attention during code reviews.
What I would suggest is a small immutable timer object holding the caption and start time:
const doPrint = true # assuming this is a global flag in your code
MyTimer(message) = MyTimer(message, time())
print_timer(timer) = doPrint && @printf("%s: %.2f seconds", timer.message, time() - timer.start_time)
julia> timer = MyTimer("doing stuff");
julia> # do stuff
doing stuff: 1.94 seconds
It is fast, and should be fast enough under almost all circumstances, but note that it does incur an additional dereference to get from the array object to the raw data. Using a tuple can be faster.