0

regarding performance with java code: which action would be better and why?:

given the following array for example:

int[] arr = new int[n];//n is a random int

Which method would you choose to increment parts of arr for the best speed performance?

arr[i++] = x;//x and i are random ints

or

arr[i] = x;
++i;
3
  • 1
    It is immediately obvious to anyone, both man and machine, that these two pieces of code require precisely the same thing to happen. So why would you expect one to perform differently from the other? Any tool that provided inferior behavior with one of these over the other would be a terrible tool that you shouldn't use if you care at all about performance and certainly wouldn't use if you cared at this kind of super-micro-detail level. Commented Mar 26, 2015 at 22:09
  • @DavidSchwartz It is immediately obvious to anyone - really? Don't know what the compiler will do in this situation (maybe optimize it away) but the post increment should require a temporary and the pre increment not... Commented Mar 26, 2015 at 22:21
  • @tomse Both can be implemented either with or without a temporary, and I'd expect a sane implementation to use a temporary for either both or for neither, depending on what was best on that particular platform. Commented Mar 26, 2015 at 22:24

1 Answer 1

5

I would forget about performance in this one and choose the first because it's easier to read, understand and maintain than the other.

Why to forget about performance? Because this is a premature optimization and will save nanoseconds (if any). Since there's no great performance improvement when choosing between any of these, then look at other factors.

Sign up to request clarification or add additional context in comments.

7 Comments

The exception being if for some reason you had an unusual situation where the second one made the rationale behind the code clearer. For example, if you might need to comment separately on each aspect of the code. (Which is unlikely, but it can happen.)
Would you say they're both equal though? Just for general knowledge :)
If they're not precisely the same, then you should use the one that better reflects the intention behind the code.
@NerdOnline because both pieces of code lead to the same result. Unless for some unknown reason i variable is shared across several threads and you have to make sure that arr[i] can be accesible in your thread, but I find this very uncommon and a very odd design.
Fair enough, will accept this as the answer as soon as I'm allowed to, cheers :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.