i'm implementing 2d array , concerned efficiency of implementation detail, 2d array interface should provide 2 essential methods:
(assume array fixed size, specified when creating, no dynamic size change)
getobjectatrow:column:
setobjectatrow:column:
enumerateusingblock:^(id obj, nsuinteger row, nsuinteger column, bool *stop)
implementation:
array of arrays (nsmutablearray)
having nsmutablearray of size rowcount , each element in nsmutablearray of size columncount, getter row array row array object @ specified column, setter use same technic. enumerator uses 2 enumeration block, 1 going through row arrays , each row array enumerator objects.
linear array (nsmutablearray)
having nsmutablearray of actual objects, getter , setter calculate index using:
index = row * columncount + column;
enumerator goes through linear array, , calculate row & column by:
row = index / columncount column = index % columncount
c array (assume element struct not class object , size predefined)
so have:
mystruct elements[row_count][column_count] then use in usual c way, getter/setter getting/setting:
elements[row][column] and enumeration using 2 loops
my concerns:
which 1 more efficient? feel c array sounds more efficient, bit hard memory management when using arc?
which 1 better? linear array or array of arrays? is, faster production/division get/set object in linear array, or faster using array of arrays?
thanks
the fastest option c array, , if care performance shouldn't wrap in objective c class, use c struct or straight variable instead.
but easiest, almost-efficient way use 1d nsmutablearray , inline wrapper functions:
inline id getobjectat( nsmutablearray *o, int row, int col ) { return [o objectatindex: row * my_fixed_width_here + col]; } inline void setobjectat( nsmutablearray *o, int row, int col, id value ) { return [o replaceobjectatindex: row * my_fixed_width_here + col withobject: value]; } the functions inlined, there's still objective-c function lookup perform (objectatindex/replaceobjectatindex). performance hit negligible; worry if benchmarking shows significant.
for implementing c array: memory management easy; add loop in dealloc function release every element, , careful in set function (retain new object then release previous object). you'll need set copying , serialisation/deserialisation functions might want, , nil items when initing. arc, can configure per-file, disable object's .m file.
Comments
Post a Comment