Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I speed up this C# function / SQL insert?

This code serializes an array of integers then inserts it into a sql table. It isn't as fast as I need it to be. Could I be doing anything more efficiently?

Thanks!

    public void SetItem(long Id, int[] items)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            foreach (int d in items)
            {
                var bin = BitConverter.GetBytes(d); //Serialize
                stream.Write(bin, 0, bin.Length);
            }
            var array = stream.ToArray();

            using (SqlCommand cmd = new SqlCommand("INSERT INTO Items(Id, Item, DateCreated) VALUES (@Id, @binaryValue, @dateCreated)", sqlConnection))
            {
                cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, array.Length).Value = array;
                cmd.Parameters.Add("@Id", SqlDbType.BigInt).Value = Id;
                cmd.Parameters.Add("@dateCreated", SqlDbType.DateTime2).Value = DateTime.Now;
                cmd.ExecuteNonQuery();
            }
        }
    }
like image 738
user404068 Avatar asked Dec 01 '22 03:12

user404068


1 Answers

I advise you to divide this function in two. One regarding the byte array the other for insertion into the DB.

Then run profiling and see if you byte array code is slow or if it is a db problem.

Maybe you are trying to accelerate something that isn't slow :)

like image 93
Marino Šimić Avatar answered Dec 04 '22 07:12

Marino Šimić