当我将数组传递给函数/子例程时会发生什么?

发布于 2024-12-19 11:21:02 字数 305 浏览 3 评论 0原文

以前我从来没有想过这个问题,但是最近我一直在担心一些事情。在 Fortran90(95) 中,假设我创建了一个非常大的数组

Integer :: X(1000000)

,然后编写了一个将该数组作为参数的函数。当我将数组传递给函数(如 myfunc(X))时,运行时到底发生了什么?

整个数组是否按值传递并在函数内构造一个新副本?(成本高昂)
或者编译器只是将某种引用或指针传递给数组?(便宜)

数组的维数或函数的声明有区别吗?

I had never thought about this before, but lately I've been worried about something. In Fortran90(95), say I create a really big array

Integer :: X(1000000)

and then I write a function that takes this array as an argument. When I pass the array to the function (as in myfunc(X)) what exactly happens during run time?

Does the entire array get passed by value and a new copy constructed inside the function?(costly)
Or does the compiler simply pass some sort of reference or pointer to the array?(cheap)

Do the dimension of the array or the declaration of the function make a difference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

樱花落人离去 2024-12-26 11:21:02

在 Fortran 90 中,与大多数其他编程语言一样,数组是通过引用传递的(从技术上讲,这通常是对数组第一项的引用)。在 Fortran 90 中,非数组值通常也通过引用传递。因此,您不必担心传递的参数的大小,因为它们不会被复制,而是简单地通过引用传递。

In Fortran 90 , as in most other programming languages, arrays are passed by reference (technically, this is often a reference to the first item of the array). In Fortran 90, non-array values are also usually passed by reference. So, you needn't worry about the size of the parameters you pass, since they won't be copied but will, instead, be passed simply by reference.

伪心 2024-12-26 11:21:02

您不想做的一件事是:

INTEGER :: X(1:1000,1:1000,1:1000)
CALL myRoutine(X(2:999,2:999,2:999))

由于某种原因, myRoutine 无法在数组的边界上进行操作。它无法传递对数组切片的引用,因为它在内存中不连续。因此它创建一个临时数组并从 X 复制值。不用说这非常慢。但是,即使指定切片,一维数组也不应该出现这个问题,因为它们在内存中仍然是连续的。

The one thing you don't want to do is something like:

INTEGER :: X(1:1000,1:1000,1:1000)
CALL myRoutine(X(2:999,2:999,2:999))

where myRoutine cannot operate on the bounds of the array for some reason. It cannot pass the reference to the slice of the array since it not contiguous in memory. So it creates a temporary array and copies the values from X. Needless to say this is very slow. But you shouldn't have that issue with 1D array, even when specifying slices, as they are still contiguous in memory.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文