I’m doing some exercises in the ThinkJulia book.
Specifically, I try to solve the exercise 10-10:
Write a function that reads the file
words.txtand builds an array with one element per word. Write two versions of this function, one using
push!and the other using the idiom
t = [t..., x]. Which one takes longer to run? Why?
Here is my code:
function version1(filename::String) array =  open(filename) do file for line in readlines(file) push!(array, line) end end array end function version2(filename::String) array =  open(filename) do file for line in readlines(file) array = [array..., line] end end array end @time println(version1(joinpath("..", "words.txt"))) @time println(version2(joinpath("..", "words.txt")))
When running two function, I observed that
version1 prints the array after running function while
version2 hangs for a while and then print the array.
version 1: 3.709137 seconds (4.47 M allocations: 115.453 MiB, 0.39% gc time, 2.21% compilation time) version 2: 77.762709 seconds (5.06 M allocations: 96.644 GiB, 1.11% gc time, 0.14% compilation time)
What actually runs under 2 function? Why did we see the big gap between them? Thank you.