Trigger Optimization 101: Return Quickly

Using 'return' efficiently in your code makes a huge difference in performance.

return quicklyWhere you place a return in your code makes a huge difference in performance.

We're back once again for more trigger optimization goodness. Our goal for this series: to help trigger writers create fast, well-formed triggers to maximize their value. If you're just jumping into the series now, make sure you check out our first post, Trigger Optimization 101: Exception Handling, for a quick tip on defensive programming.

With that out of the way, let's jump into our topic for this week: returning quickly.

Let's Bounce

Watch this video (1:54) for a demonstration of this week's topic: returning quickly.

 

Every line of code in a trigger takes cycles to execute, whether it's a debug call(more on this in a future post), variable declaration, or otherwise. Keeping this in mind, let's take a look at an example trigger:

var uri = HTTP.uri;
var client_ip = Flow.client.ipaddr;
var server_ip = Flow.server.ipaddr;
var query     = HTTP.query;
var cookies   = HTTP.cookies;
var method    = HTTP.method;

if (uri.indexOf('extrahop') === -1) {
    return;
}

// Do other stuff

In the above code, we declare several variables and fill them with information around the flow. Next, we then check to see if this is an HTTP transaction we want to take further action against (commit metrics, create an application, etc) using an If block. How could we optimize this to be better?

The answer is: return sooner.

We know our criteria for filtering out HTTP transactions: if the URI does not contain "extrahop". In order to check this criteria, we only need to create a single variable, uri. We can then check this variable, and only if it meets our criteria do we create our other variables. The new code will then look like:

var uri = HTTP.uri;

if (uri.indexOf('extrahop') === -1) {
    return;
}

var client_ip = Flow.client.ipaddr;
var server_ip = Flow.server.ipaddr;
var query     = HTTP.query;
var cookies   = HTTP.cookies;
var method    = HTTP.method;

// Do other stuff

By ordering our trigger with the return statement as soon as possible in the trigger execution, we can avoid wasting the execution cycles creating the other variables until we are sure we'll actually use them. To see this optimization in practice, check out the video.

That covers our topic for this week. Take a look at some of the triggers you've written in the past, and see if there's room for improvement. As always, tell us if there are any specific topics you would like to see covered, or if there are any questions we can answer in the comments.

Check out the first post in this series: Trigger Optimization 101: Exception Handling

Start your ExtraHop demo

Subscribe to our Newsletter

Get the latest from ExtraHop delivered straight to your inbox.