Skip to content

ByteaTextToByteArray conversion optimization - #51

Closed
Rungee wants to merge 1 commit into
npgsql:masterfrom
Rungee:master
Closed

Rungee wants to merge 1 commit into
npgsql:masterfrom
Rungee:master

Conversation

@Rungee

@Rungee Rungee commented Sep 6, 2013

Copy link
Copy Markdown
Contributor

Hi Francisco,

I have my own GIS project that mostly deals with reading of geospatial data. Working with PostGIS I use Npgsql.
By doing some profiling of my application I've found out that the function ByteaTextToByteArray in the BasicBackendToNativeTypeConverter class takes too much time to convert data from hex format.
Then I tried to find a way to speed up the conversion.
It seems that current implementation is not well optimized:

     MemoryStream ms = new MemoryStream(); <-  is unnecessary object
        if (BackendData.StartsWith("\\x"))
        {
            // PostgreSQL 8.5+'s bytea_output=hex format
            for (byteAPosition = 2; byteAPosition < byteAStringLength; byteAPosition += 2)
            {
                byte value = Convert.ToByte(BackendData.Substring(byteAPosition, 2), 16);     <- substring and byte conversion is slow

In my implementation I tried to avoid those slow parts. The results of the tests are the following

Table with linestrings:
Size: 483 MB
Rows: 2260348
Master branch: 46117 ms
Optimized version: 12566 ms (10639 ms)
Speeding-up factor: 3.66

Table with points:
Size: 383 MB
Rows 1167910
Master branch: 35185 ms
Optimized version: 9219 ms (8187 ms)
Speeding-up factor: 3.81

As you can see we can significantly improve the performance of the conversion.
In the commit you can find some commented lines of code where I played with unsafe code which also gives some performance gain.

The time values in brackets were obtained using unsafe code and the following function
internal static Object ToBinary(NpgsqlBackendTypeInfo TypeInfo, char[] BackendData, Int16 TypeSize, Int32 TypeModifier)
instead of
internal static Object ByteaTextToByteArray(NpgsqlBackendTypeInfo TypeInfo, String BackendData, Int16 TypeSize, Int32 TypeModifier)

As you can see from two functions the conversion from char[] to string in the case of bytea data is superfluous.
Please take into consideration that the last improvement was not commited. I hope that you can catch the idea of the last improvement.

@glenebob

glenebob commented Sep 9, 2013

Copy link
Copy Markdown
Contributor

Hi Rungee,

This is Francisco's project, not mine, but I saw your pull request and since it is related to code I've been working on lately, I was interested and wanted to take a look at it.

This is a great improvement! I've tested it, and poked at it, and I think it's great. I initially tested it against the \x encoder that I recently added to the project, and found that your decoder took maybe 1/3 longer to decode a bytea sequence than it took for my code to encode it. That seemed a bit lop-sided to me, so I wanted to see if there was a way to improve the decoder. It seems that because the decoder is saddled with error checking that the encoder is not, that the difference actually makes sense; in fact, with the (b == 255) check commented out, and the inlined code in place as noted below, it's very nearly equal in speed to the encoder. After spending the time to root that out, I have a couple things to report that you may find useful.

  1. I wanted to try and trim the lookup arrays if possible, since they seem kind of large and redundant. What I found is that you can eliminate one of the arrays (I eliminated the high order array in my tests), and use bit shifting in its place, like so:
        byte b1 = (byte)(LookupTableLow[str[index++]] << 4);
        byte b2 = LookupTableLow[str[index]];

Whatever difference in speed is indiscernible on my machine (a Windows 8 laptop). Which surprised me, quite frankly. Maybe you would be interested in checking my results.

  1. Your commented out code, which does everything inline, rather than calling LookupLow() and LookupHigh(), is about 25% faster on my machine, which indicates that the function calls are fairly expensive. Purely in the name of speed optimization, I would vote for using the inlined code rather than the function calls.

Note that I copied your code into a test project and beat it up in isolation. I only call the ToByte() functions and record total time spent on a very large array, so any overhead elsewhere in the driver code is entirely eliminated.

So, nice work! This is a very worthwhile improvement in my opinion.

-Glen

@Rungee

Rungee commented Sep 9, 2013

Copy link
Copy Markdown
Contributor Author

Thank you Glen for your time to check this approach. Since this optimization was done about 6 months ago I don't remember what was the reason of commenting the inlined version. I was so busy that just had no time to contribute it.
The inline code on my machine gives only 10% of performance gain.

I've tried to make some further improvement which consists in using char pointer of the input string.
Here is the code:
fixed (char* chr = BackendData)
{
fixed (byte* p = &result[0])
{
byte* ptr = p;
char* ch = chr;
ch += 2;

          for (byteAPosition = 2; byteAPosition < byteAStringLength; byteAPosition += 2)
          {
             *ptr = FastConverter.ToByte(ch, byteAPosition);

             ptr++;
             ch += 2;
          }
        }
      }

10613 ms - pointers for result and input string, inlined version of the ToByte function.
11234 ms - only inlined content of ToByte
12828 ms - without inline code and pointers

It is clear that using pointers we can improve the performance up to 20% more.

If Francisco does not want to use any unsafe code it would be great to have a possibility to use this optimization through #ifdef directive controls which can be switched on/off by the developer.

@franciscojunior

Copy link
Copy Markdown
Member

Hi, guys!

Sorry for delay to comment. I was in vacation. :)

I think this is an excellent discussion.

Very nice patch, @Rungee .

Indeed I'd better have Npgsql using only safe code.

I think we could get unsafe code by using #ifdef directive as @Rungee suggested. The biggest problem would be when creating the release files. We would need to create one version with safe code and another one with unsafe code.

Another implication is that according to this post: http://stackoverflow.com/questions/706495/what-are-the-implications-of-using-unsafe-code using unsafe code restricts the assembly to a full trust environment.
In the past I received reports from users who use Npgsql in servers where Partial Trust environment is used. If I recall correctly, I even had to change this line: https://github.com/franciscojunior/Npgsql2/blob/master/src/Npgsql/AssemblyInfo.cs#L19 to make it work again on Partial Trust when compiled with .Net 4.0 and above.

@glenebob

Copy link
Copy Markdown
Contributor

Hi Rungee,

PR 52 changes BackendData (in ByteaTextToByteArray()) from string to byte[]. The easiest way to get your PR working again is to change the (string BackendData) to (byte[] bBackendData), and add:

string BackendData = BackendEncoding.UT8Encoding.GetString(bBackendData);

Doing it that way should render the same performance as you achieved already.

By having your new code operate directly on the byte[], you'll see an even greater performance increase. I'll be happy to modify the code to work that way if you want, once Francisco merges it.

-Glen

@Rungee

Rungee commented Sep 22, 2013

Copy link
Copy Markdown
Contributor Author

Hi Glen,

I have seen your amazing work concerning a lot of improvements and optimization. That's a really great work!
Please, feel free to modify the part of my code.

Best,
Max

@franciscojunior

Copy link
Copy Markdown
Member

Hi @Rungee ! Would it be possible for you to rebase your work in the new master? This way when I merge your code you will get your deserved credits! :)

If a rebase is too much troublesome, you can open a new PR and close this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants