未初始化的字节数组是Scala

时间:2015-12-06 19:38:37

标签: arrays performance scala initialization

ByteArrayOutputStream

中有这样的代码
private void button_Click(object sender, EventArgs e)
{
    var button = sender as Button;
    foreach (DataGridViewRow item in this.dataGridView1.Rows)
    {
        //This is the last row, ignore it.
        if (item.IsNewRow)
            continue;

        //Compare value of cell1 with button text
        //I supposed button.Tex is the value that you want to compare with cusid 
        if (item.Cells[1].Value.ToString() == button.Text)
        {
            //Make row editable
            item.ReadOnly = false;

            //Select the logout cell
            this.dataGridView1.CurrentCell = item.Cells[5];
        }
        else
        {
            //Make row readonly
            item.ReadOnly = true;
        }

    }
}

你能不能在Scala中做同样的事情而不浪费时间在每个元素上进行不必要的初始化?

2 个答案:

答案 0 :(得分:6)

这样做的一种方法是使用随播广告对象的.ofDim方法:

scala> val buf = Array.ofDim[Byte](10)
buf: Array[Byte] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

code behind it与@ Nyavro的答案相同,所以他的解决方案实际上跳过了一个电话。)

.ofDim可能有用的一个实例是创建多维数组(最多五个维度)时:

scala> val buf = Array.ofDim[Byte](5, 5)
buf: Array[Array[Byte]] = Array(Array(0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0), Array(0, 0, 0, 0, 0))

Array companion object包含其他有用的方法来创建数组(例如.fill.tabulate方法)

答案 1 :(得分:3)

Scala等价物:

val buf = new Array[Byte](size)