I am experiencing a dilemma. Let me explain it with two functions:

# Takes vector.magnitude(), vector.x, vector.y and uses it somewhere
def func1(vector, {other parameters 1}):

# Takes vector.magnitude(), vector.x, vector.y and uses it somewhere
def func2(vector, {other parameters 2}):

It is not uncommon that func2 is called right after func1 with the same vector variable. There is a redundant calculation for the vector magnitude, as it is calculated twice. Should the vector magnitude instead be a separate function parameter? If not, what should be changed to alleviate this problem?

  • 3
    Possible duplicate of Is micro-optimisation important when coding? – gnat May 23 '18 at 0:11
  • Do you know these functions to be calculation hotspots from doing a profile? – user1118321 May 23 '18 at 3:30
  • @gnat I do not think this applies as my question is much more specific to a certain case. Also, it is not necessarily an improvement that would only improve "micro-seconds in code." In the scenario I explained, the program would be ~2x faster, assuming everything else in the functions are fairly inexpensive. – Andrew Gazelka May 24 '18 at 4:17
  • @user1118321 I am assuming that the calculations are going to be somewhat expensive and highly repeated. – Andrew Gazelka May 24 '18 at 4:19
  • How is this question related to Java? – Hulk May 24 '18 at 9:50

Calculating the vector magnitude should be a method of the vector class. Then it can cache and reuse the result as necessary or advisable. Burdening higher-level logic with micro-decisions like this is bad for readability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.