Extremely fast way to clone the values of a jagged array into a second array?

前端 未结 4 1436
青春惊慌失措
青春惊慌失措 2020-12-09 05:28

I am currently working on an application that is responsible for calculating random permutations of a jagged array.

Currently the bulk of the time in the applicati

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 06:16

    Either of these should work for you. They both run in about the same amount of time and are both much faster than your method.

    // 100 passes on a int[1000][1000] set size
    
    // 701% faster than original (14.26%)
    static int[][] CopyArrayLinq(int[][] source)
    {
        return source.Select(s => s.ToArray()).ToArray();
    }
    
    // 752% faster than original (13.38%)
    static int[][] CopyArrayBuiltIn(int[][] source)
    {
        var len = source.Length;
        var dest = new int[len][];
    
        for (var x = 0; x < len; x++)
        {
            var inner = source[x];
            var ilen = inner.Length;
            var newer = new int[ilen];
            Array.Copy(inner, newer, ilen);
            dest[x] = newer;
        }
    
        return dest;
    }
    

提交回复
热议问题