Performance comparison of array of arrays vs multidimensional arrays

后端 未结 4 1774
Happy的楠姐
Happy的楠姐 2020-12-18 03:18

When I was using C++ in college, I was told to use multidimensional arrays (hereby MDA) whenever possible, since it exhibits better memory locality since it\'s allocated in

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-18 03:47

    Is this worth the effort? Is this too low level of an optimization issue for a language like Java?

    Generally speaking, it is not worth the effort. The best strategy to to forget about this issue in the first version of your application, and implement in a straight-forward (i.e. easy to maintain) way. If the first version runs too slowly for your requirements, use a profiling tool to find the application's bottlenecks. If the profiling suggests that arrays of arrays is likely to be the problem, do some experiments to change your data structures to simulated multi-dimensional arrays and profile see if it makes a significant difference. [I suspect that it won't make much difference. But the most important things is to not waste your time optimizing something unnecessarily.]

    Should we just abandon arrays and use Lists even for primitives?

    I wouldn't go that far. Assuming that you are dealing with arrays of a predetermined size:

    • arrays of objects will be a bit faster than equivalent lists of objects, and
    • arrays of primitives will be considerably faster and take considerably less space than equivalent lists of primitive wrapper.

    On the other hand, if your application needs to "grow" the arrays, using a List will simplify your code.

提交回复
热议问题