【发布时间】:2021-10-07 07:31:51
【问题描述】:
我正在尝试从小部分构建一个字符串以发送到 websocket。
#Example input from somewhere else
side = "left"
jumps = 3.482
string_of_id = "Caterpillar"
sz = 100
speller = "lower"
function stringConcat(side::String, px::Float64, ticker::String, sz::Int64, ordType::String)
return string("""{"id":\"""", string(abs(rand(Int64))), """\",\"message\":[{\"Key1\":""", string(rand(1:10000)), """,\"Leftorright\":\"""", side,
"""\",\"numjump\":""", string(jumps), """,\"jumpid\":\"""", string_of_id, """\",\"sz\":""", string(sz), """,\"speller\":\"""", type_of_speller,
"""\",\"mode\":\"json\"}],"operation":"jumping\"}""")
end
# 255.780 ns (9 allocations: 911 bytes)
有没有办法预先分配以避免分配,或者我可以使用其他技巧?现在我认为这么多的分配是相当多的。
【问题讨论】:
-
您可以使用
IOBufferdocs.julialang.org/en/v1/base/io-network/#Base.IOBuffer 来重用缓冲区。但是您还应该确保避免使用您似乎正在使用的全局变量。无论如何,911bytes 对于你在这里做的事情来说似乎相当低。 -
它看起来像一个 JSON。我会构建一个 Dict,然后使用 JSON3.jl 生成 JSON 字符串。
-
没有全局变量,这些都是从别处传递的参数
标签: performance julia heap-memory allocation