On Fri, Apr 15, 2016 at 3:44 PM,  <[email protected]> wrote:
> 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).

In either cases, it doesn't seems necessary to use `eval` at all,
especially not by constructing a string and parse it.
You can just push to an array directly and it would be much faster.
Calling `eval` at runtime (i.e. not when you are construction a
module) is always a bad idea especially for performance.

>
> Thank you,
> Bogumił

Reply via email to