Java Performance - ArrayLists versus Arrays for lots of fast reads

前端 未结 12 1541
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 20:20

I have a program where I need to make 100,000 to 1,000,000 random-access reads to a List-like object in as little time as possible (as in milliseconds) for a cellular automa

12条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 20:37

    One possibility would be to re-implement ArrayList (it's not that hard), but expose the backing array via a lock/release call cycle. This gets you convenience for your writes, but exposes the array for a large series of read/write operations that you know in advance won't impact the array size. If the list is locked, add/delete is not allowed - just get/set.

    for example:

      SomeObj[] directArray = myArrayList.lockArray();
      try{
        // myArrayList.add(), delete() would throw an illegal state exception
        for (int i = 0; i < 50000; i++){
          directArray[i] += 1;
        }
      } finally {
        myArrayList.unlockArray();
      }
    

    This approach continues to encapsulate the array growth/etc... behaviors of ArrayList.

提交回复
热议问题