 # Code Optimization

### Interesting things about software development and code optimization

Hi friends,

today we are going to work on something that looks and sounds crazy, we are going to speed up multiplication and division.

First, lets look into a code that we will try to speed up:

```            double p1 = 0, p2 = 0;
int count = 100000000;

Stopwatch sw = new Stopwatch();
Int32 a = 0, b = 0;            sw.Start();            for (int i = 0; i < count; i++)            {                a = i;                a *= 2;                b += a;            }            sw.Stop();            p1 = sw.ElapsedMilliseconds;            Console.WriteLine(sw.ElapsedMilliseconds + " : " + a);```

As you can see the code just measures time that multiplication takes, on my PC this cycle takes about 160 ms.

Now lets add similar code but optimized and we are expecting it will be faster:

-

```        static void Main(string[] args)        {            double p1 = 0, p2 = 0;            int count = 100000000;            Stopwatch sw = new Stopwatch();            Int32 a = 0, b = 0;
sw.Start();
for (int i = 0; i < count; i++)            {                a = i;                //multiply by 2                a *= 2;                b += a;            }            sw.Stop();
p1 = sw.ElapsedMilliseconds;            Console.WriteLine(sw.ElapsedMilliseconds + " : " + a + " : " + b);
sw.Reset();            sw.Start();            b = 0;
for (int i = 0; i < count; i++)            {                a = i;                //multiply by 2                a <<= 1;                b += a;            }
sw.Stop();            p2 = sw.ElapsedMilliseconds;
Console.WriteLine(sw.ElapsedMilliseconds + " : " + a + " : " + b);            Console.WriteLine("percent faster: " + 100.0 / p1 * (p1 - p2));            Console.WriteLine("times faster: " + (p1 / p2));            Console.ReadLine();        }```

If you will compile it and run (make sure you compile it in Release mode and run outside of Visual Studio) you will see almost no difference

in speed between these two cases of multiplication. On my PC it shows something like that:

161 : 199999998 : 1774919424
157 : 199999998 : 1774919424
percent faster: 2.48447204968944
times faster: 1.02547770700637

but we can say that the result almost the same. Interesting and not really, but do not be  sad, every next step will amaze you ;)

## Another type

So, the next step is to test it with another type of integer - Int64 (or long), and what we see? We see that now it is about two times faster, here is my result:

846 : 199999998 : 9999999900000000
342 : 199999998 : 9999999900000000
percent faster: 59.5744680851064
times faster: 2.47368421052632

ha, interesting? So using simple bit scrolling to multiply integer value by 2, 4, 8, 16 ... much faster than multiplication itself.

Lets continue with division.

## Division

Ok, now, lets go through the same steps but this time with division, here is the code:

```        static void Main(string[] args)        {            double p1 = 0, p2 = 0;            int count = 100000000;
Stopwatch sw = new Stopwatch();            Int32 a = 0, b = 0;
sw.Start();
for (int i = 0; i < count; i++)            {                a = i;                //div by 2                a /= 2;                b += a;            }
sw.Stop();
p1 = sw.ElapsedMilliseconds;
Console.WriteLine(sw.ElapsedMilliseconds + " : " + a + " : " + b);
sw.Reset();            sw.Start();            b = 0;
for (int i = 0; i < count; i++)            {                a = i;                //div by 2                a >>= 1;                b += a;            }
sw.Stop();            p2 = sw.ElapsedMilliseconds;
Console.WriteLine(sw.ElapsedMilliseconds + " : " + a + " : " + b);            Console.WriteLine("percent faster: " + 100.0 / p1 * (p1 - p2));            Console.WriteLine("times faster: " + (p1 / p2));            Console.ReadLine();        }```

Compile and run it and you will see that the speed also almost the same:

180 : 49999999 : -1728753792
158 : 49999999 : -1728753792
percent faster: 12.2222222222222
times faster: 1.13924050632911

And as you may expect changing from Int32 to Int64 should be even more faster, and this is true, and in my case it more than 8 times faster:

2978 : 49999999 : 2499999950000000
344 : 49999999 : 2499999950000000
percent faster: 88.4486232370719
times faster: 8.65697674418605

So, the main thing here is that multiplication and division on non-native types are complex operations that involve more processor consumption than simple bit scrolling.

On the other hand the Int64 type is not native type for 32 bit environment and it takes more time to operate with it.

But if you will compile this code as x64 and run it under 64 bit operating system, you will see completely another result, here is mine:

229 : 49999999 : 2499999950000000
151 : 49999999 : 2499999950000000
percent faster: 34.061135371179
times faster: 1.51655629139073

this is because of under 64 bit operating system the Int32 and Int64 are native types (means a CPU register may handles whole value).

One more thing is the Any CPU compilation - it seems not so good as you may expect.

Thank you, and do not hesitate to comment it.

Hi friends,

today I'm going to show you one possible way to speed up the COUNT(*)  performance in case when you need to know the total amount of rows of your select query with paging.

Here is the example of my first and slow query:

Select

COUNT(*) OVER () as TotalCount

, ID

, OwnerID

, Name

, [Description]

, keywords

From [dbo].[tblData]

where pState = N'a' and [status] <> 'P'

and (@FilterBy = 0 OR @FilterBy = TypeID)

Order By DateAdded Desc

OFFSET @p0 ROWS FETCH NEXT @p1 ROWS ONLY;

this query did take from 4 seconds up to 9 seconds selecting 315000 rows from about 450000 rows -

that is really slow. It seems like OVER () overloads the query itself (but this is just my guess).

Also converting from nchar to char takes a lot of time, so I did change it (notice the N letter before string)

After some time of thinking and playing with that around, I did come to the following solution:

select @rowstotal = count(*)

From [dbo].[tblData]

where pState = 'a' and [status] <> 'P'

and (@FilterBy = 0 OR @FilterBy = TypeID)

select

@rowstotal as TotalCount

, ID

, OwnerID

, Name

, [Description]

, keywords

From [dbo].[tblData]

where pState = 'a' and [status] <> 'P'

and (@FilterBy = 0 OR @FilterBy = TypeID)

Order By DateAdded Desc

OFFSET @p0 ROWS FETCH NEXT @p1 ROWS ONLY;

(pay attention that to calculate total number of rows to be selected you do not need ordering. I think count(*) with ordering works much slower)

Now this query takes up to 1 second to select the same 315000 rows from about 450000 that is minimum 4 times faster :)

I'm not sure if this is really best solution as I'm not a DBA master :)

but in my case it sped up the query enough.

Thank you.