Skip to content

Commit 6a42574

Browse files
committed
reduce memory allocations in lms() and lts()
1 parent e18b034 commit 6a42574

3 files changed

Lines changed: 16 additions & 10 deletions

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
- More explicit return types, drop `Dict` with `Dict{String, Any}` or `Dict{String, Vector}`
44
- Add `Julia v.1.10` to GitHub actions
5+
- Reduce memory allocation in `lts()` and `lms()`
56

67

78
# v0.11.3

src/lms.jl

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,22 +68,26 @@ function lms(X::AbstractMatrix{Float64}, y::AbstractVector{Float64}; iters = not
6868
iters = minimum([500 * p, 3000])
6969
end
7070
bestobjective = Inf
71-
bestparamaters = []
72-
bestres = []
71+
bestparamaters = zeros(Float64, p)
72+
bestres = zeros(Float64, n)
73+
origres = zeros(Float64, n)
7374
indices = collect(1:n)
7475
kindices = collect(p:n)
76+
betas = zeros(Float64, p)
77+
res = zeros(Float64, n)
78+
7579
for _ = 1:iters
7680
try
7781
k = rand(kindices, 1)[1]
7882
sampledindices = sample(indices, k, replace = false)
79-
betas = X[sampledindices, :] \ y[sampledindices]
80-
origres = y .- X * betas
81-
res = sort(origres .^ 2.0)
83+
betas .= X[sampledindices, :] \ y[sampledindices]
84+
origres .= y .- X * betas
85+
res .= sort(origres .^ 2.0)
8286
m2 = res[h]
8387
if m2 < bestobjective
84-
bestparamaters = betas
88+
bestparamaters .= betas
8589
bestobjective = m2
86-
bestres = origres
90+
bestres .= origres
8791
end
8892
catch e
8993
@warn e

src/lts.jl

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -150,16 +150,17 @@ function lts(X::AbstractMatrix{Float64}, y::AbstractVector{Float64}; iters=nothi
150150

151151
allindices = collect(1:n)
152152
bestobjective = Inf
153-
besthsubset = []
153+
besthsubset = zeros(Int, h)
154+
subsetindices = zeros(Int, p)
154155

155156
bestobjectiveunchanged = 0
156157

157158
for _ = 1:iters
158-
subsetindices = sample(allindices, p, replace=false)
159+
subsetindices .= sample(allindices, p, replace=false)
159160
objective, hsubsetindices = iterateCSteps(X, y, subsetindices, h)
160161
if objective < bestobjective
161162
bestobjective = objective
162-
besthsubset = hsubsetindices
163+
besthsubset .= hsubsetindices
163164
bestobjectiveunchanged = 0
164165
else
165166
bestobjectiveunchanged += 1

0 commit comments

Comments
 (0)