Should I use viewstate in this case?

36 views Asked by At

I have an asset tracking device that, every few seconds, sends details about its location to a generic handler using an HTTP request. The information is then stored in a SQL database record. It works fine but I am trying to make in way that if the device is stationary, the handler stops creating new records and simply updates the "last ping" time stamp in the last record.

To achieve that, I would need a way for the handler to know that the last coordinates received are the same as those of the previous request. Other than querying the database to check what the last coordinates were, is there a way to tell if they changed or not? I was thinking of storing the values in a viewstate variable and then compare the new readings to it, but I don't know if that is efficient. Is there a more professional way to handle it?

1

There are 1 answers

2
David On

Any way you look at it, the operation you're describing is:

if (new != old)
  save new

In order to perform this operation, you need two pieces of information. old and new. This operation can be performed server-side or client-side, as long as these two pieces of information are present.

So options would include:

  1. Client always sends new to the server. Server reads old from previous data (a database) and performs operation.
  2. Client always sends old and new to the server. For this, the client would have to retain a copy of old somewhere. (View State is an option, but it doesn't really matter how it's stored. Could just be a JavaScript variable, really.)
  3. Client performs this operation and only conditionally sends new to the server. For this, the client would still have to retain a copy of old somewhere.

There are pros and cons to each. 3 is the least chatty over the network. 1 and 2 perform the logic server-side where you have more control over it. 1 doesn't require the client to know anything at all. 2 assumes the client's data is correct, which could present risks. Etc.

If the goal is to keep the client "dumb" and keep all the logic on the server, I'd personally opt for 1. You can prevent re-querying of the database by caching the information in the server-side application or some high performance cache system.

You might even offload the comparison to the database itself and no application code knows/cares whether new != old. A stored procedure handles the logic.

Alternatively, if the goal is to reduce resource usage then 3 becomes pretty appealing. Network activity can be slower, less reliable, less available (when on wireless connections in remote areas for example), and potentially more expensive than database activity.

The question then quickly becomes... What are you trying to optimize? To answer that, first you need to concretely measure and define your bottleneck.