0
0
Rest APIprogramming~5 mins

Safe methods vs unsafe methods in Rest API - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Safe methods vs unsafe methods
O(n)
Understanding Time Complexity

We want to understand how the time it takes to handle safe and unsafe REST API methods changes as the number of requests grows.

How does the server's work increase when processing these different methods?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


// Example REST API handler
function handleRequest(request) {
  if (request.method === 'GET' || request.method === 'HEAD') {
    return readData(request);
  } else {
    return modifyData(request);
  }
}

function readData(request) {
  // Reads data from database
}

function modifyData(request) {
  // Updates database and triggers side effects
}
    

This code handles safe methods (GET, HEAD) by reading data and unsafe methods by modifying data.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Reading or modifying data per request.
  • How many times: Once per request, but modifyData may trigger extra operations like database writes or side effects.
How Execution Grows With Input

As the number of requests increases, the server does more work for each request.

Input Size (n)Approx. Operations
1010 reads or writes
100100 reads or writes
10001000 reads or writes

Pattern observation: The work grows directly with the number of requests, whether safe or unsafe.

Final Time Complexity

Time Complexity: O(n)

This means the time to handle requests grows linearly with how many requests come in.

Common Mistake

[X] Wrong: "Safe methods like GET take no time or less time than unsafe methods."

[OK] Correct: Both safe and unsafe methods require processing; unsafe methods may do more work, but safe methods still take time to read and respond.

Interview Connect

Understanding how different REST methods affect server work helps you explain API performance and design choices clearly in interviews.

Self-Check

"What if modifyData triggered multiple database writes per request? How would the time complexity change?"