简体   繁体   English

优化F#字符串连接

[英]Optimize F# string concatenation

I'm building a MySql query that batch inserts 4096 records at once. 我正在构建一个批处理插入4096条记录的MySql查询。 The actual insert is quite fast but the bottleneck is generating the query. 实际插入非常快,但瓶颈是生成查询。 Any hints on optimizing this? 优化这一点的任何提示? The string generation is currently taking about 18 times longer than the query. 字符串生成目前比查询长约18倍。

                    let builder = StringBuilder(524288)
                    Printf.bprintf builder
                        "
                         INSERT INTO %s
                             (`ID`,
                              `Tag`,
                              `Port`,
                              `Excess`,
                              `Return`,
                              `StartDate`,
                              `EndDate`
                              ) 
                          values "
                        x.evaluationstable

                    evaluations
                    |> Seq.iter(fun (e) ->
                        Printf.bprintf builder 
                            " (%d, '%s', '%s', %A, %A, %A, %A), "
                            e.ID
                            e.Tag
                            e.Port
                            e.Excess
                            e.Return
                            (e.StartDate.ToString(x.datetimeformat))
                            (e.EndDate.ToString(x.datetimeformat))
                    )

Try using StringBuilder.AppendFormat instead of Printf.bprintf . 尝试使用StringBuilder.AppendFormat而不是Printf.bprintf When I made this change in my example of your question, I saw a huge performance increase (~80x). 当我在你的问题的例子中做出这个改变时,我看到了巨大的性能提升(~80x)。

evaluations
|> Seq.iter (fun (e) ->
    builder.AppendFormat(
        " ({0}, '{1}', '{2}', {3}, {4}, {5}, {6}), ",
        e.ID,
        e.Tag,
        e.Port,
        e.Excess,
        e.Return,
        (e.StartDate.ToString("MM/dd/yyyy")),
        (e.EndDate.ToString("MM/dd/yyyy"))
    ) |> ignore
)

I would try to avoid embedding the data directly into SQL to start with. 我会尽量避免将数据直接嵌入到SQL中。 Use a sequence of prepared statements with parameters, and set those parameters to the values (without formatting them). 使用一系列带参数的预准备语句,并将这些参数设置为值(不对其进行格式化)。 That's safer and is likely to be a lot more efficient. 这更安全,可能更有效率。

Whether you can still do this in a batch rather than in several separate calls just within the same transaction, I'm not sure. 你是否仍然可以在一个批次中而不是在同一个交易中的几个单独的调用中执行此操作,我不确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM