Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best practice for returning objects

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading