Is ArrayList.size() method cached?

2019-02-11 19:58发布

I was wondering, is the size() method that you can call on a existing ArrayList<T> cached? Or is it preferable in performance critical code that I just store the size() in a local int?

I would expect that it is indeed cached, when you don't add/remove items between calls to size().

Am I right?

update
I am not talking about inlining or such things. I just want to know if the method size() itself caches the value internally, or that it dynamically computes every time when called.

7条回答
爷的心禁止访问
2楼-- · 2019-02-11 20:55

Why would it need to be? ArrayList implements a List interface that is backed by an array, after all.

I would assume it to just have a size member, that is incremented when you insert things and decremented when you remove, and then it just returns that.

I haven't looked at more than the API docs now, though.

查看更多
登录 后发表回答