@@ -18,7 +18,6 @@ contains
18
18
${t1}$, intent(in), optional :: prepend(:), append(:)
19
19
${t1}$, allocatable :: y(:)
20
20
integer :: size_prepend, size_append, size_x
21
- ${t1}$, allocatable :: work(:)
22
21
integer :: n_, i
23
22
24
23
n_ = optval(n, 1)
@@ -38,16 +37,24 @@ contains
38
37
return
39
38
end if
40
39
41
- allocate(work(size_x + size_prepend + size_append))
40
+ #! Use a quick exit for the common case, to avoid memory allocation.
41
+ if (size_prepend == 0 .and. size_append == 0 .and. n_ == 1) then
42
+ y = x(2:) - x(1:size_x-1)
43
+ return
44
+ end if
45
+
46
+ block
47
+ ${t1}$ :: work(size_x + size_prepend + size_append)
42
48
if (size_prepend > 0) work(:size_prepend) = prepend
43
49
work(size_prepend+1:size_prepend+size_x) = x
44
50
if (size_append > 0) work(size_prepend+size_x+1:) = append
45
51
46
52
do i = 1, n_
47
53
work(1:size(work)-i) = work(2:size(work)-i+1) - work(1:size(work)-i)
48
54
end do
49
-
55
+
50
56
y = work(1:size(work)-n_)
57
+ end block
51
58
52
59
end function diff_1_${k1}$
53
60
@@ -58,7 +65,6 @@ contains
58
65
${t1}$, allocatable :: y(:, :)
59
66
integer :: size_prepend, size_append, size_x
60
67
integer :: n_, dim_, i
61
- ${t1}$, allocatable :: work(:, :)
62
68
63
69
n_ = optval(n, 1)
64
70
if (n_ <= 0) then
@@ -87,19 +93,32 @@ contains
87
93
return
88
94
end if
89
95
96
+ #! Use a quick exit for the common case, to avoid memory allocation.
97
+ if (size_prepend == 0 .and. size_append == 0 .and. n_ == 1) then
98
+ if (dim_ == 1) then
99
+ y = x(2:, :) - x(1:size_x-1, :)
100
+ elseif (dim_ == 2) then
101
+ y = x(:, 2:) - x(:, 1:size_x-1)
102
+ end if
103
+ return
104
+ end if
105
+
90
106
if (dim_ == 1) then
91
- allocate(work(size_x+size_prepend+size_append, size(x, 2)))
107
+ block
108
+ ${t1}$ :: work(size_x+size_prepend+size_append, size(x, 2))
92
109
if (size_prepend > 0) work(1:size_prepend, :) = prepend
93
110
work(size_prepend+1:size_x+size_prepend, :) = x
94
111
if (size_append > 0) work(size_x+size_prepend+1:, :) = append
95
112
do i = 1, n_
96
113
work(1:size(work,1)-i, :) = work(2:size(work)-i+1, :) - work(1:size(x, 1)-i, :)
97
114
end do
98
115
99
- y = work(1:size(work)-n_, :)
116
+ y = work(1:size(work,1)-n_, :)
117
+ end block
100
118
101
119
elseif (dim_ == 2) then
102
- allocate(work(size(x, 1), size_x+size_prepend+size_append))
120
+ block
121
+ ${t1}$ :: work(size(x, 1), size_x+size_prepend+size_append)
103
122
if (size_prepend > 0) work(:, 1:size_prepend) = prepend
104
123
work(:, size_prepend+1:size_x+size_prepend) = x
105
124
if (size_append > 0) work(:, size_x+size_prepend+1:) = append
@@ -108,6 +127,7 @@ contains
108
127
end do
109
128
110
129
y = work(:, 1:size(work,2)-n_)
130
+ end block
111
131
112
132
end if
113
133
0 commit comments