【问题标题】:Julia building strings with no allocationJulia 构建没有分配的字符串
【发布时间】: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)

有没有办法预先分配以避免分配,或者我可以使用其他技巧?现在我认为这么多的分配是相当多的。

【问题讨论】:

  • 您可以使用IOBuffer docs.julialang.org/en/v1/base/io-network/#Base.IOBuffer 来重用缓冲区。但是您还应该确保避免使用您似乎正在使用的全局变量。无论如何,911bytes 对于你在这里做的事情来说似乎相当低。
  • 它看起来像一个 JSON。我会构建一个 Dict,然后使用 JSON3.jl 生成 JSON 字符串。
  • 没有全局变量,这些都是从别处传递的参数

标签: performance julia heap-memory allocation


【解决方案1】:

https://github.com/JuliaString/Strs.jl 生态系统包含很多试图提高 Julia 中字符串性能的包,包括带有 https://github.com/JuliaString/StrLiterals.jl 的字符串文字。

对于会经常重复使用的字符串,您还可以查看https://github.com/JuliaString/InternedStrings.jl

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2017-06-14
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多