简体   繁体   中英

Is setPosition(1, 2) a lot faster than setPosition(new Point(1, 2))

Two method implementations:

public void setPosiotion(int x, int y) { //do nothing }

public void setPosiotion(Point point) { //do nothing }

What if I had to call setPosition() 1 billion times, would the method that doesn't require to create a new Point work noticeably faster?

It could make a small difference, but its likely to be less than it time it takes you to write the longer expression. Sometimes your time and your efficiency is more important.

Even more important than the time it takes to write, is the time spent maintaining the code which can be 3x the time taken to develop it. This suggests maintainability should be your main concern.

In short; write simple, clearly understood code and it will often perform well and be the most effective in the long run.

What if I had to call setPosition() 1 billion times, would the method that doesn't require to create a new Point work noticeably faster?

It depends what the setPosition method does.

  • If the method simply uses the x and y values from the Point then it is probably faster not to create / pass a Point object.

  • If the method immediately creates a Point to hold the x and y values that you passed, then creating the Point yourself could be faster.

This is complicated by the fact the latest JVMs could use escape analysis to deduce that the Point object doesn't need to be created as a heap object. And on the flip side, it depends how many levels of method call (etcetera) the x and y values need to be passed through.

In short, it is hard to predict.


Finally, your assumption that setPosition will be called a billion times is suspect... unless you've actually profiled the application. And even if it is valid, these calls might still make an insignificant contribution to the overall application execution time.

Profile first, and then optimize.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM