Skip to content

Instantly share code, notes, and snippets.

@nalimilan
Last active January 2, 2016 06:08
Show Gist options
  • Save nalimilan/8261056 to your computer and use it in GitHub Desktop.
Save nalimilan/8261056 to your computer and use it in GitHub Desktop.
A small puzzle...
function test1(x::AbstractVector)
dims = [10]
a = zeros(Int, dims...)
for i in 1:length(x)
a[1] += 1
end
a
end
function test2(x::AbstractVector)
dims = [10]
a = zeros(Int, dims...)
for i in 1:length(x)
a[1] = 1
end
a
end
function test3(x::AbstractVector)
dims = (10,)
a = zeros(Int, dims)
for i in 1:length(x)
a[1] += 1
end
a
end
a = [1:10000000]
precompile(test1, (a,))
precompile(test2, (a,))
precompile(test3, (a,))
@time test1(a)
@time test2(a)
@time test3(a)
test1(a) == test3(a)
@vtjnash
Copy link

vtjnash commented Jan 4, 2014

julia> precompile(test1, (typeof(a),))

julia> precompile(test2, (typeof(a),))

julia> precompile(test3, (typeof(a),))

julia> @time test1(a)
elapsed time: 1.239536913 seconds (319984040 bytes allocated)

julia> @time test2(a)
elapsed time: 0.272075941 seconds (408 bytes allocated)

julia> @time test3(a)
elapsed time: 0.025167431 seconds (248 bytes allocated)

@ivarne
Copy link

ivarne commented Jan 4, 2014

In 1 and 2 the dimensionality of a can't be inferred from the type of dims, because array length is nor part of the type.

a[i] += 1 is an alias for setindex!(a,i,getindex(a,i)+1), and apparently that requires a temporary variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment