Skip to content

Bind optimizations - #77

Merged
franciscojunior merged 12 commits into
npgsql:masterfrom
glenebob:bind
Nov 18, 2013
Merged

franciscojunior merged 12 commits into
npgsql:masterfrom
glenebob:bind

Conversation

@glenebob

Copy link
Copy Markdown
Contributor

Francisco,

Here we have some more Bind optimizations.

-Glen

@glenebob

Copy link
Copy Markdown
Contributor Author

I think this PR is really more bug fixes than optimization. I think the extended query command flow is correct now, in addition to being a bit more network efficient.

-Glen

@franciscojunior

Copy link
Copy Markdown
Member

I'm reviewing this PR.

@glenebob

Copy link
Copy Markdown
Contributor Author

And I'm adding to it. Gotta keep you on your toes :)

-Glen

On Sat, Oct 12, 2013 at 2:38 PM, Francisco Figueiredo Jr. <
[email protected]> wrote:

I'm reviewing this PR.

—
Reply to this email directly or view it on GitHubhttps://github.com//pull/77#issuecomment-26206600
.

@franciscojunior

Copy link
Copy Markdown
Member

In NpgsqlCommand.BindParameters(),

in the code:

 if (parameterValues[i] == null) {
     parameterFormatCodes[i]= (Int16)FormatCode.Binary;
                    } else {
     parameterFormatCodes[i] = parameters[i].TypeInfo.SupportsBinaryBackendData ? (Int16)FormatCode.Binary : (Int16)FormatCode.Text;
                    }

I think this type of information about the parameterFormatCodes can be obtained in the Prepare call which would alleviate this checking in the Bind phase.
Note that this parameterFormatCode information is still valid as long as the type of the parameter isn't changed even if its value is.

I think we can optimize a lot by gathering the max information possible in the Prepare call.

Another thing I noticed, when thinking about the common way of using the prepared calls:

NpgsqlCommand.Parameters.Add()
NpgsqlCommand.Prepare()

NpgsqlCommand.ExecuteReader();
NpgsqlCommand.Parameters change values
NpgsqlCommand.ExecuteReader()
...

I think this PR is the way to go, although, unless I'm missing something, I think it is optimized for the situation where the parameter values aren't changed. Because the bound property changed is triggered whenever there is a change in the type, size, and value. I think the value trigger needs to have some more checks because if the value of the parameter is changed but its datatype isn't, the information about size, parameterformatcode and others can be reused.

When I went now to check the documentation for sqlcommand.prepare , I found the following:

"Before you call Prepare, specify the data type of each parameter in the statement to be prepared. For each parameter that has a variable length data type, you must set the Size property to the maximum size needed. Prepare returns an error if these conditions are not met."

Which solves the little optimization exception I was talking about in the mail about the performance tests
where I say:
"Also, an optimization I think we could do is the following:
As we know the number of parameters and its length, for non varying length
data types, like string, we could reuse some of the already calculated
values like the message length and the sum of
_parameterFormatCodes.Length."

Per documentation of sqlcommand.Prepare, those varying length data types I was talking about must have its maximum size specified before calling prepare. This way its length can be reliably calculated.

I don't know if I'm being clear here, but I think that we have a lot of information we can use to do a lot of optimization when using prepared statements.

I hope I didn't talk too much :)

I may not be able to follow up with you about this issue tonight, but please, let your comments (or better yet, your commits) here and I'll check them as soon as I can.

Thank you, Glen! You are doing an extraordinary job here!

@franciscojunior

Copy link
Copy Markdown
Member

I just had another thought about the Prepare optimization:

What if we, based on the fact that the prepare method has been called, already convert the value of the parameter in the Bind/Execute byte[] format when its value is set instead of waiting for the last minute to convert it? I don't know if this would give us a big performance improvement, but if we associate that with the idea that we may have scenarios where the developer only changes some of the parameter values but not all of them, we would end up alleviating a lot of conversion by reusing the values already converted.

This is just a last minute crazy idea in this optimization context we are talking about.

@glenebob

Copy link
Copy Markdown
Contributor Author

On Sun, Oct 13, 2013 at 3:38 PM, Francisco Figueiredo Jr. <
[email protected]> wrote:

I just had another thought about the Prepare optimization:

What if we, based on the fact that the prepare method has been called,
already convert the value of the parameter in the Bind/Execute byte[]
format when its value is set instead of waiting for the last minute to
convert it? I don't know if this would give us a big performance
improvement, but if we associate that with the idea that we may have
scenarios where the developer only changes some of the parameter values but
not all of them, we would end up alleviating a lot of conversion by reusing
the values already converted.

Maybe I'm missing your point here, but the code in BindParameters() only
does the conversion work on parameters that have changed in some way since
the last Bind. If you have ten parameters, and only change one between
Executes, only that one will be converted on subsequent Binds.

Granted, the code is not very smart. Any change to the number of
parameters causes them all to be re-converted on the next Bind. Baby steps
:) I don't understand yet all the nuances to the extended query system, so
I wanted to make sure not to break anything, while still achieving a good
optimization.

I get the feeling that the parameter types, sizes, and names could possibly
be concreted after Prepare. In fact, the parameter list could be
constructed with proper types, lengths, and empty values by Prepare. Then,
the developer would only need to set their values before each Execute. In
that scenario, the user would be prevented from changing types and sizes,
and from adding/deleting parameters after Prepare. I have not explored
this at all.

-Glen.

@glenebob

Copy link
Copy Markdown
Contributor Author

And just to add, I was pushing to get this to a stable stopping point so
you could release a beta. But since you've pushed the release out two
weeks, that will give me a lot of time to dig even deeper into this.

-Glen

On Sun, Oct 13, 2013 at 3:56 PM, Glen Parker [email protected] wrote:

On Sun, Oct 13, 2013 at 3:38 PM, Francisco Figueiredo Jr. <
[email protected]> wrote:

I just had another thought about the Prepare optimization:

What if we, based on the fact that the prepare method has been called,
already convert the value of the parameter in the Bind/Execute byte[]
format when its value is set instead of waiting for the last minute to
convert it? I don't know if this would give us a big performance
improvement, but if we associate that with the idea that we may have
scenarios where the developer only changes some of the parameter values but
not all of them, we would end up alleviating a lot of conversion by reusing
the values already converted.

Maybe I'm missing your point here, but the code in BindParameters() only
does the conversion work on parameters that have changed in some way since
the last Bind. If you have ten parameters, and only change one between
Executes, only that one will be converted on subsequent Binds.

Granted, the code is not very smart. Any change to the number of
parameters causes them all to be re-converted on the next Bind. Baby steps
:) I don't understand yet all the nuances to the extended query system, so
I wanted to make sure not to break anything, while still achieving a good
optimization.

I get the feeling that the parameter types, sizes, and names could
possibly be concreted after Prepare. In fact, the parameter list could be
constructed with proper types, lengths, and empty values by Prepare. Then,
the developer would only need to set their values before each Execute. In
that scenario, the user would be prevented from changing types and sizes,
and from adding/deleting parameters after Prepare. I have not explored
this at all.

-Glen.

@glenebob

Copy link
Copy Markdown
Contributor Author

Rebased and pushed (force).

@franciscojunior

Copy link
Copy Markdown
Member

No, no. You got it right. Your code already rebinds only the changed parameters. :)
I focused only in the parameterformatcodes when I made my first comments :) Sorry for that. Then, this part of "cache" of the parameter values between execute calls is already done!

And I think your code is very smart! And I agree with you: as you said, baby steps. I think each new idea build up on the previous step so we can get further :)
I think your attitude of looking for not breaking anything is super correct. Thanks for taking that in consideration!

Yes, when the developer changes anything in the size, number of parameters and type this would invalidate everything the prepare call would have optimized and this would be like if the developer has not called Prepare at all.

I think you will get a deeper understanding of the extended query in no time and this will reflect in a much better Npgsql! :)

Thank you very much for your feedback, suggestions and commits, Glen! You are awesome!

@franciscojunior

Copy link
Copy Markdown
Member

Btw, I made some tests using your SpeedTests and can see a big improvement when using Prepared statements with this PR applied.

Here is what I got:

git glenebob-bind

Running Npgsql2010.NpgsqlTests.NpgsqlTests.SpeedTests.ParameterizedSelectBigIntArrayRoundTrip ...
Elapsed: 00:00:10.0043772, Queries: 412; 41,18/second
Total test running time: 10023ms

Running Npgsql2010.NpgsqlTests.NpgsqlTests.SpeedTests.ParameterizedSelectBigIntArrayRoundTripPrepared ...
Elapsed: 00:00:10.0019006, Queries: 3636; 363,53/second
Total test running time: 10038ms

Running Npgsql2010.NpgsqlTests.NpgsqlTests.SpeedTests.ParameterizedSelectBigIntRoundTrip ...
Elapsed: 00:00:10.0004308, Queries: 22029; 2202,81/second
Total test running time: 10017ms

Running Npgsql2010.NpgsqlTests.NpgsqlTests.SpeedTests.ParameterizedSelectBigIntRoundTripPrepared ...
Elapsed: 00:00:10.0004087, Queries: 30358; 3035,68/second
Total test running time: 10039ms

Running Npgsql2010.NpgsqlTests.NpgsqlTests.SpeedTests.ParameterizedSelectByteaArrayRoundTrip ...
Elapsed: 00:00:10.0159704, Queries: 138; 13,78/second
Total test running time: 10035ms

Running Npgsql2010.NpgsqlTests.NpgsqlTests.SpeedTests.ParameterizedSelectByteaArrayRoundTripPrepared ...
Elapsed: 00:00:10.0260231, Queries: 364; 36,31/second
Total test running time: 10072ms

Running Npgsql2010.NpgsqlTests.NpgsqlTests.SpeedTests.ParameterizedSelectByteaRoundTrip ...
Elapsed: 00:00:10.0079195, Queries: 167; 16,69/second
Total test running time: 10029ms

Running Npgsql2010.NpgsqlTests.NpgsqlTests.SpeedTests.ParameterizedSelectByteaRoundTripPrepared ...
Elapsed: 00:00:10.0187807, Queries: 461; 46,01/second
Total test running time: 10057ms

We can see that we have performance improvements in the order between 300% to 800% ! Excellent!

@glenebob

Copy link
Copy Markdown
Contributor Author

I'm afraid this has become a nightmare for PR #74 :(

@glenebob

Copy link
Copy Markdown
Contributor Author

I ran a couple speed comparisons to the Java driver, and found it was still quite a bit faster with prepare statements. I used a packet sniffer to compare our backend communications with the Java driver's and found that that it only sends a Describe (portal) with the first Bind/Execute. By having Npgsql only send Describe once as well, I was able to improve performance on a simple repeated (SELECT :param) by about 20% in my testing. The Java driver is still about 10-12% faster on this test, but we're getting there :)

-Glen

@roji

roji commented Oct 19, 2013

Copy link
Copy Markdown
Member

That's some really great work Glen :) I wish I had more time to help out with this :)

@glenebob

Copy link
Copy Markdown
Contributor Author

Thanks Shay! ;)

-Glen

@franciscojunior

Copy link
Copy Markdown
Member

That's awesome, Glen! As soon as I get back from my vacation I'll work on this pull request and others, like the #74 :-)

@glenebob

Copy link
Copy Markdown
Contributor Author

Rebased.

@glenebob

Copy link
Copy Markdown
Contributor Author

Francisco,

Don't merge this yet. I stumbled on a bug tonight involving arrays of money - something the test suite didn't hit. My brain's gone mush, so I'll figure it out tomorrow, add a test, and let you know.

-Glen

@franciscojunior

Copy link
Copy Markdown
Member

Ok. I'll wait. Thanks for the heads up.

@glenebob

Copy link
Copy Markdown
Contributor Author

Francisco,

The bug isn't related to this body of work, it was caused by PR #80. I'm sending up a new PR to fix it. I think this PR is ready to go.

-Glen

@glenebob

Copy link
Copy Markdown
Contributor Author

Rebased.

Optimize bind to cache message length.
Only convert parameters for bind if needed.
Do not Sync() after writing Bind to the wire; wait until after Execute.
Remove unneeded Sync()'s.
BindComplete response should not yield, as it gives us no information we can use.
Rearrange and cleaned some of the extended query code for better readabliity and consistency.
The Flush and Sync messages are now singletons, available by their static Default fields.
The Describe and Execute messages now live across many Executes without change, and set _messageLength at constrution.
No need for the Parse message to live outside of Prepare().
Improve OO design of NpgsqlDescribe by splitting it into an abstract base class and two sub classes.
Split NpgsqlState by moving the two backend response handlers into their own files.
Fix BackendEncoding.UTF8Encoding to be readonly.
Minor cleanups.
@glenebob

Copy link
Copy Markdown
Contributor Author

Rebased.

@franciscojunior

Copy link
Copy Markdown
Member

I think this PR is almost ready to go.

I just noticed that the NpgsqlStartupPacket header was partially removed :)

Other than that, I think it is ok.

The Flush command is never used anymore, and it is easily confused with Stream.Flush(); remove support for it.
Simplify and mske more consistent some of the query pathways.
Avoid calling Stream.Flush() in multiple locations; call it in ProcessBackendResponses() instead.
Remove a bunch of redundant/unused code.
The two Process*BackendResponse*() functions are now the only entry points into that functionality.
NopgsqlQuery now constructs with a connector and query text (byte[] or string).
The "unknown" type supports binary decoding now.
cancelRequestCalled parameter is never set true; remove it.
Optimize ExecuteBlind() a little more.
Make sure to block the notification thread before writing query messages to the wire.
Add connection string value "AlwaysPrepare".
Implement "AlwaysPrepare" support on NpgsqlCommand.
Refactor Prepare code so that calling Prepare() from within GetReader() avoids redundant sanity checks.
When a previously prepared statement command text is changed, automatically re-Prepare (if needed) before the next Execute.
Complete implementation of "ApplicationName" connection string value (I hope).
Hide enum DescribeTypeCode properly.
Don't save lastRowDescription in the backend response handlers; save it in DataReader instead.
Send Portal Describe only once; save the row description for subsequent Executes.
Use a more efficient path to DataRow disposal on protocol version V3.
Shorten plan and portal names for a small network bandwidth savings.
Interlocked.Increment not needed for plan and portal number increments.
Bump the buffer size on BufferedStream to 8192.
Remove incorrect usage of the Sync message - its purpose is for directing PG in case there's an error, not recovering from an error after it happens.
Remove useless try/catch constructs.
…here's nothing to describe; handle this scenario properly.
@glenebob

Copy link
Copy Markdown
Contributor Author

I have no idea how I did that... I made it go away via rebase and edit
commit, as that change has no place in history.

-Glen

On Sun, Nov 17, 2013 at 6:19 PM, Francisco Figueiredo Jr. <
[email protected]> wrote:

I think this PR is almost ready to go.

I just noticed that the NpgsqlStartupPacket header was partially removed :)

Other than that, I think it is ok.

—
Reply to this email directly or view it on GitHubhttps://github.com//pull/77#issuecomment-28671397
.

@franciscojunior

Copy link
Copy Markdown
Member

The Eagle has landed!

franciscojunior added a commit that referenced this pull request Nov 18, 2013
@franciscojunior
franciscojunior merged commit 09634e5 into npgsql:master Nov 18, 2013
@franciscojunior

Copy link
Copy Markdown
Member

Thanks for fixing the StartupPacket header. :)

@glenebob glenebob mentioned this pull request Nov 19, 2013
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.

4 participants