Home > Back-end >  Best practice for returning objects
Best practice for returning objects

Time:03-06

hope you're having a good day.

I'm making a simple node.js api, and I wondered which of these is the most performant way to return a response.

I use this class for returning responses:

class Response {
    constructor(statusCode, error, data){
        this.status = statusCode;
        this.error = error;
        this.data = data;
    }
}

export default const handleResponse =  (statusCode = 200, error = '', data = {}) => {
    return new HandlerResponse(statusCode, error, data);
}

Sometimes I use it this way:

const response = handleResponse();

if(condition) {
    response.error = 'An error ocurred';
    response.status = 400;
    return response;
} else {
    response.error = 'Some other error';
    response.status = 404;
    return response;
}

And sometimes I use it like this:

if(condition) {
    return handleResponse(400, 'An error ocurred')
} else return handleResponse(404, 'Some other error')

Would be a difference between this two in performance? Which should I use?

CodePudding user response:

The two implementations are almost the same

Both do the following;

  1. Allocate an object in memory
  2. Add a numerical property to the object
  3. Add a string to the object

The only practical difference between the two is that the first option also allocates an empty object if you leave that parameter unspecified, whereas the second leaves that field undefined.

The only way to know which is faster is to test them both

To determine which of the two is faster, you would have to test them both. On one hand, the empty object (the optional "data" parameter) should theoretically slow the first implementation slightly. On the other hand, its possible the javascript engine might optimise the first one better because it doesn't have a branch in the middle.

CodePudding user response:

The fact that the first implementation is allocating memory, is the less performant solution of the two. However, performance gains would not be realized between either implementation because of how negligible they would be. Javascript, like most popular languages, is extremely performant and so most of the time it's best to focus on readability more than performance when it comes to determining the best implementation.

  • Related