It's not really very inefficient. Compare:

julia> f(x, y, z) = return x^2, y^3, z^4;

julia> g(a, b, c) = f(a, b, c)[3];

julia> @code_llvm g(1.0, 1.0, 1.0)

define double @"julia_g;767954"(double, double, double) {
top:
  %3 = call double @pow(double %2, double 4.000000e+00), !dbg !525
  ret double %3, !dbg !525
}

julia> function g(a, b, c)
           _, _, v = f(a, b, c)
           v
       end;

julia> @code_llvm g(1.0, 1.0, 1.0)

define double @"julia_g;767955"(double, double, double) {
top:
  %3 = call double @pow(double %2, double 4.000000e+00), !dbg !528
  ret double %3, !dbg !530
}

If the return values are bits types, the optimizer is smart enough that 
there's no overhead to pulling unused variables out of tuples. (In this 
case, f was inlined, so g doesn't even compute x^2 or y^3.) At present,  _, 
a, b = f(x, y, z) will actually be more efficient than a, b = f(x, y, 
z)[2:3], since the latter will allocate a new tuple on the heap, although 
that could probably be improved.

If the return values are not bits types, or if the return type of f is not 
inferrable, there will be slight overhead to pulling an unused value out of 
a tuple, but in the former case the time to allocate the unused return 
values will be vastly greater, and in the latter case the type instability 
would be a performance bottleneck no matter what.

Simon

On Wednesday, October 15, 2014 11:23:20 AM UTC-4, Gray Calhoun wrote:
>
> Hi everyone, if a function returns multiple values, is there an idiomatic 
> way to discard all but (say) the 3rd value returned? For example:
>
> f(x, y, z) = return x^2, y^3, z^4
> _, _, v = f(1, 2, 3)
>
> expresses the intent to only use the third value returned, but surely is 
> inefficient.
>
> Thanks!
>

Reply via email to