Home > Blockchain >  Is there any benefit to changing the values of the session properties only where necessary?
Is there any benefit to changing the values of the session properties only where necessary?

Time:02-01

I noticed how some people do this. It got me wondering if it is beneficial. For instance, I check if a given condition is met by either of the properties of a session. Then this is done again, separately for each property of the object.

Let's say I have two counters. Once one of them exceeds 1, both should get reset:

let notes = [];
if (req.session.counters[0] > 1 || req.session.counters[1] > 1) {
    notes.push("A counter has exceeded the limit.");
    if (req.session.counters[0] > 1) {
        req.session.counters[0] = 0;
    }
    if (req.session.counters[1] > 1) {
        req.session.counters[1] = 0;
    }
}

It is pretty much the same as this:

let notes = [];
if (req.session.counters[0] > 1 || req.session.counters[1] > 1) {
    notes.push("A counter has exceeded the limit.");
    req.session.counters[0] = 0;
    req.session.counters[1] = 0;
}

So, is there any benefit? Such as faster execution? Or it's pretty much pointless?

CodePudding user response:

In your first example, if counters[0] === 5 and counters[1] === 0.5, after the if-statement, counters[0] === 0 and counters[1] === 0.5 while in the second example, both would be 0. This doesn't matter if the counter can't go negative or be a fractional value.


Ignoring that, it would depend on how your session values are persisted.

If you have a single server, you might store the values in memory. In that case, there is no reason to use example #1.

If you are using multiple servers & users can hop between them but should have the same session, then values should be persisted in a database/a key-value store. All servers would read values from that database/key-value store. Writing a single integer is very little overhead, no matter what database you're using but if you had larger writes, example #1 might be worth it. Writing to disk or—"even worse"—to the network is a lot slower than memory.

It depends on your application if readability trumps a micro-optimization. While veering towards an opinion-based answer, I'd say in this case it absolutely does.

  •  Tags:  
  • Related