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:

class Response {
    constructor(statusCode, error, data){
        this.status = statusCode;
        this.error = error; = 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?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x