3

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}):
    pass

# 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?](https://softwareengineering.stackexchange.com/questions/99445/is-micro-optimisation-important-when-coding) – gnat May 23 '18 at 00:11
  • Do you know these functions to be calculation hotspots from doing a profile? – user1118321 May 23 '18 at 03: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. – andrewgazelka May 24 '18 at 04:17
  • @user1118321 I am assuming that the calculations are going to be somewhat expensive and highly repeated. – andrewgazelka May 24 '18 at 04:19
  • How is this question related to Java? – Hulk May 24 '18 at 09:50
  • @Hulk Sorry, I didn't specify this. I am applying this principle to Java code, even though the pseudocode is not written in Java. – andrewgazelka May 24 '18 at 16:25

1 Answers1

8

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.

Kilian Foth
  • 107,706
  • 45
  • 295
  • 310