Could someone help me to understand why the following code works slowly and 
how to make it run faster?

function run()
    # this is fast
    s1 = string("x = [0", join([string(", ", i) for i in 1:256]), "]")
    p1 = parse(s1)
    @time eval(p1)
    @time eval(p1)

    # here starts the slow part
    s2 = string("x = ['0'", join([string(", ", i) for i in 1:128]), "]")
    p2 = parse(s2)
    @time eval(p2)
    @time eval(p2)

    s3 = string("x = ['0'", join([string(", ", i) for i in 1:256]), "]")
    p3 = parse(s3)
    @time eval(p3)
    @time eval(p3)

    s4 = string("x = ['0'", join([string(", ", i) for i in 1:192]), "]")
    p4 = parse(s4)
    @time eval(p4)
    @time eval(p4)
    println("done")
end

run()

I understand that arrays of Any would evaluate slower than arrays of 
specified type but there seems to be a qualitative difference in how they 
are handled. It seems that the problem is with compilation of the code as 
after we run eval(p3) then consecutive run is fast and eval(p4) is also 
fast.

The comparable code in Python:

exec("x = [0"+"".join([", " + str(i) for i in range(1, 513)]) + "]")
exec("x = ['0'"+"".join([", " + str(i) for i in range(1, 513)]) + "]")

runs fast in both cases.

The problem here is an artificial example. The actual situation occurred 
when I was trying to include code that constructed a long vector of strings 
consisting of ASCIIString and UTF8String entries (some of the string 
literals included code contained only ASCII characters and some did not eg. x 
= ["a", "ą"], the actual vector was much longer).

Thank you,
Bogumił

Reply via email to