In Julia, are there cpu/memory dissadvantages when functions that modify their arguments return nothing?

huangapple go评论72阅读模式
英文:

In Julia, are there cpu/memory dissadvantages when functions that modify their arguments return nothing?

问题

我有一个关于在Julia中声明函数的一般问题。如果我的新函数修改其参数之一,它应该返回:
a. 修改后的参数?
或者
b. 什么都不返回?

我的意思是,如果函数修改其参数,即使函数不返回参数,我也会在相应对象中看到修改。

返回/不返回修改后的参数会有什么缺点/优点。

这里有一个例子:

英文:

I have a general question about how to declare functions in Julia. If my new function modifies one of its parameters, should it return:
a. the modified parameter?
or
b. nothing?

I mean, if the function modifies its argument, I will see the modifications in the respective object even if the function does not return it.
What would be the dissadvantages/advantages or returning/not returning the modified parameter.

An example here:

julia> a= [2,3,5]
3-element Vector{Int64}:
 2
 3
 5

#Variant 1, the function returns its modified argument
julia> function addA!(a)
       a .= a .+ 5
       return a
       end
addA! (generic function with 1 method)

julia> addA!(a)
3-element Vector{Int64}:
  7
  8
 10

#Variant 2, the function returns nothing
function addA!(a)
a .= a .+ 5
       return nothing
       end
addA!

addA!(a)

答案1

得分: 3

第一个变体在Julia标准库中广泛使用,因此通常更受青睐。例如,请参阅push!map!rand!mul!等。这种风格符合Julia的“一切皆表达式”哲学,并且很方便,因为函数通常可以被它们的原地版本替代,而不需要其他任何更改:例如,sort(filter(isodd, A)) => sort!(filter!(isodd, A))。它还使得实现原地函数的分配版本变得容易:

foo(A) = foo!(copy(A)) # 标准库中的常见习惯

在性能方面没有不利之处。

英文:

The first variant is used extensively in the Julia standard libraries, so this style is preferred in general. For instance see push!, map!, rand!, mul!, etc. This style fits with Julia's "everything is an expression" philosophy, and is convenient because functions can often be substituted with their in-place versions without any other changes: e.g. sort(filter(isodd, A)) => sort!(filter!(isodd, A)). It also makes implementing the allocating version of an in-place function easy:

foo(A) = foo!(copy(A)) # common idiom in the stdlib

There's no disadvantage in terms of performance.

huangapple
  • 本文由 发表于 2023年6月11日 21:11:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450621.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定