Search code examples
timebig-ocpunotation

Queston about big O notation


Let's say I have getNumber() return me a integer stored in a class that I instantiated in main.

public int getNumber()
{
  return number;
}

Would the above code take O(1) and would the below code take O(2)? Or am I misunderstanding how O notation works in terms of CPU cycles to complete a operation?

public int getNumber()
{
  int myNumber = number;
  return myNumber;
}

So rephrasing my question, would returning an object's variable in one line be the same performance-wise as declaring another variable to hold that object's variable and then returning it in another line?


Solution

  • Big-O notation isn't about counting the exact number of CPU cycles, but about counting orders of magnitude in relation to some varying size (e.g., the length of an input). Here, both functions have a constant runtime which is not dependent on any additional size, and thus are both O(1).

    (By the way, in any real-world scenario, I'd expect a decent compiler to inline the int myNumber = number line, and make the two function declarations essentially identical)