0

这是一个 iOS 项目。我正在修改我的 dataController 的一部分以使用 2D C 数组而不是嵌套的 NSMutableArrays 来优化速度。我发现我需要对数组的各个部分执行数千个整数加法运算,并且对象模型相当慢。

我的数组维度目前是 710 x 55,710 数字是动态的。我还有 5 个其他相同大小的数组,将来可能会更多,因此我需要避免使用 NSArrays。

我不会发布整个源代码,所以只发布相关部分:

@implementation MMEventDataController

int **wbOcMatrix = NULL;
int numEvents = 0;

-(void)generateMatrix {

for (NSDictionary *item in JSONData) {

{...}
// Here I parse some JSON data and bring part of it into newEvents.wb which is an
// NSMutableArray of ints. These can be ints 1 thru 55, which represent various
// flags that can be set. Only 5 flags will be inside each newEvent.wb. 
{...}

// Create some empty C arrays. This part is probably where I go wrong.

    wbOcMatrix = (int **) realloc (wbOcMatrix, (numEvents+1) * sizeof(int *));

    wbOcMatrix[numEvents] = malloc (55 * sizeof(int));

    int wbOcArray[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};


// Here we find which 5 flags are set in newEvent.wb and set the corresponding index of
// wbOcArray to 1.

    for (id object in newEvent.wb) {

        int v = wbOcArray[[object intValue]-1];
        v++;
        wbOcArray[[object intValue] -1] = v;
        }

// Then we bring the new wbOcArray into the next index of the wbOcMatrix and increment.

    wbOcMatrix[numEvents] = wbOcArray;
    numEvents++;

}

// This process repeats for all items in the JSON data, at the moment is 710, thus
// creating an array 710 x 55.

二维数组似乎创建得很好,这意味着我有适当大小的数组,其中包含数据,但是,数组的每一行都包含相同的数据!该数据来自迭代 710。

我的怀疑是,由于我的数组是一个指针数组,每次迭代都会改变原始指针处的数据,并且所有行都指向同一个地方。那么如何为每次迭代分配新的内存空间呢?我以为这就是 malloc 的用途...

4

1 回答 1

0

你的问题在这里:

int wbOcArray[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

当循环结束时,这将自动释放。如果你NSLog(@"%p", wbOcArray);直接在上面的行之后放一个,你会看到,它总是指向同一个地址。

将此行替换为:

int* wbOcArray = (int*)malloc(sizeof(int)*55);
for(int i = 0; i < 55; i++) wbOcArray[i] = 0;

最好的,克里斯蒂安

于 2012-05-20T11:03:59.170 回答