HiroIshida
HiroIshida

Reputation: 1603

Strange slow down when using struct and loop in Julia

I made a speed-comparison between two functions with and without using struct as below, and its performance difference is huge: 0.07899 vs 0.0011 [sec]. The strange thing is that the contents of idxset in test1() and test2() are exactly the same(1...10000) but the processing time of the loop over those two are different. Note that the measurements were performed only for loops.

Could you explain how to improve my code with struct and why this happens?

struct Data
    bool
end
function test1()
    N = 10^5
    data = Data(trues(N))
    idxset = findall(data.bool)

    s=0.0
    @time for i in idxset
        s += i^2
    end
    return s
end

function test2()
    N = 10^5
    bool = trues(N)
    idxset = findall(bool)

    s=0.0
    @time for i in idxset
        s += i^2
    end
    return s
end
test1()
test2()

Upvotes: 1

Views: 191

Answers (1)

Chris Rackauckas
Chris Rackauckas

Reputation: 19132

struct Data
    bool
end

doesn't have any type information on bool, so data.bool cannot infer the type, leading to uninferred types in your function and slow code. data.bool being uninferred probably makes idxset uninferred which makes each i uninferred and slows down the arithmetic. Check this with @code_warntype. Fix this with:

struct Data
    bool::BitArray{1}
end

Upvotes: 3

Related Questions