Efficiency of method call in for loop condition

前端 未结 3 1915
忘了有多久
忘了有多久 2021-01-02 06:27

I am writing a game engine, in which a set of objects held in a ArrayList are iterated over using a for loop. Obviously, efficiency is rather important, and so

3条回答
  •  余生分开走
    2021-01-02 07:09

    By specification, the idiom

    for (String extension : assetLoader.getSupportedExtensions()) {
      ...
    }
    

    expands into

    for (Iterator it = assetLoader.getSupportedExtensions().iterator(); it.hasNext();)
    {
        String extension = it.next();
        ...
    }
    

    Therefore the call you ask about occurs only once, at loop init time. It is the iterator object whose methods are being called repeatedly.

    However, if you are honestly interested about the performance of your application, then you should make sure you're focusing on the big wins and not small potatoes like this. It is almost impossible to make a getter call stand out as a bottleneck in any piece of code. This goes double for applications running on HotSpot, which will inline that getter call and turn it into a direct field access.

提交回复
热议问题