# Logic and Speed on Computers

As I am working on a complex system that is in need of optimization, I look at the existing code and try to come up with changes that should make the code go faster.

So... today I noticed that I was doing a lot of string compare in this way:

```if(path.startsWith("m2osw/redirect/"))
{
if(path == "m2osw/redirect/permissions"))
{
}
else if(path == "m2osw/redirect/journal"))
{
}
}```

Up to here, nothing strange and looking at the logic, this means if the path starts with "m2osw/redirect" then we have to check further to see what the path is as we understand:

• "m2osw/redirect/permissions", and
• "m2osw/redirect/journal"

So I thought that I could use the endsWith() function of the QString. I also test a few other things in the real version, but that mean we would have this:

```if(path.endsWith("/permissions")) ...
if(path.endsWith("/journal")) ...```

As we can see, the strings are smaller which certainly means that the compare function will run faster. Right?

Incorrect. The endsWith() function is actually really slow, and since I thought that it could be so, I wrote a test to see whether I was right. The test runs the full compare as in the first example (a == b) and then the partial compare (a.endsWith(part of b)).

The test is part of my Snap Websites project (see string_speed.cpp).

The results are:

```j = 20000000 iterations
a = 389489
b = 766402
diff = 376913```

The number of iterations: 20 million for each test.

a is the amount of time used when comparing against the full string.

b is the amount of time used when comparing using the endsWith() function.

diff represents the difference between a and b. Here we see a difference of 377 ms. So the straight compare with == is properly optimized whereas, endsWith() does not seem to be.

So in other words, my code is already optimized as it is.