You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Remove allocations from data read/write operations #385
We currently perform a lot of needless allocation when we read and write data.
When reading a result value, a byte buffer is allocated, we read from the stream into it, we pass it to the converter code to produce a .NET type, and we discard the byte buffer. This happens here. We should be reading directly from the stream rather than using an intermediary buffer.
When writing a parameter, the .NET type is first converted into a newly allocated byte array, which then gets written to the stream and discarded. This happens here for unprepared queries. We should be directly writing the bytes to the stream rather than using an intermediary buffer.
I've studied and done some preliminary work here. To be honest, the amount of needless allocations happening inside Npgsql is staggering, since the data conversion methods all internally allocate byte arrays and return them, rather than simply writing out values to the stream.
A good case in point is converting an array of ints for sending to the backend. The array binary conversion method first allocates a MemoryStream. It then goes over each int, converts it to a (newly-allocated) byte array, and copies that byte array into the MemoryStream. As this happens, the MemoryStream may or may not reallocate its internal buffer as it fills up. At the end of the process, .ToArray() is executed on the MemoryStream, which again copies the MemoryStream contents to an external array. Finally, this array is copied into our BufferStream's buffer, to be actually written to the stream when the query is sent.
In other words, unless I've lost count, each int is copied at least 4 times. Besides the needless copying itself, all the heap allocations slows down the program considerably as the garbage collector has to clean things up later. The situation is less dramatic but fundamentally the same for all data types.
The solution is of course to pass the connector to all conversion functions, and for them to write out data directly to the stream, this way we have zero allocations and zero copies (except for the single BufferedStream, which is necessary to cut down on I/O system calls).
I've begun to do this, but am being blocked by one thing: our non-prepared parameterized query support. As part of client-side binding, the conversion methods must be called in a way that produces simple strings, which will get integrated into the query text. It will be difficult to architecture the code to support both modes (direct-to-stream and string-producing).
I think this makes the refactor/optimization depend on #370, which would eliminate client-side binding altogether and simplify everything. @Emill, you mentioned you may be interested in this (and you already worked on this area). Do you want to work on this (my async work is merged), or if you're too busy I can take a look?
I've studied and done some preliminary work here. To be honest, the amount of needless allocations happening inside Npgsql is staggering, since the data conversion methods all internally allocate byte arrays and return them, rather than simply writing out values to the stream.
Yes. I think this is one of the biggest performance blocker of Npgsql. We will get a huge performance improvement when we remove all those allocations. Also, they impose a big hit on garbage collector.
A good case in point is converting an array of ints for sending to the backend. The array binary conversion method first allocates a MemoryStream. It then goes over each int, converts it to a (newly-allocated) byte array, and copies that byte array into the MemoryStream. As this happens, the MemoryStream may or may not reallocate its internal buffer as it fills up. At the end of the process, .ToArray() is executed on the MemoryStream, which again copies the MemoryStream contents to an external array. Finally, this array is copied into our BufferStream's buffer, to be actually written to the stream when the query is sent.
:( :(
I've begun to do this, but am being blocked by one thing: our non-prepared parameterized query support. As part of client-side binding, the conversion methods must be called in a way that produces simple strings, which will get integrated into the query text. It will be difficult to architecture the code to support both modes (direct-to-stream and string-producing).
Hmmm, I see. In order to support both modes we would have duplicated code: one writing directly to the stream and another returning a byte[].
@roji , is the branch you are working on this public? If possible, I'd like to have a look at it, please. Maybe there is something I can help you with.
@franciscojunior, my idea is that if #370 we no longer need both modes: parameters should always be sent using the extended query protocol, so you never need to convert parameters for integration into a string query. #370 would make it pretty easy to complete the allocation optimization here, apart from improving performance (through binary encoding and much less parsing for non-prepared parameterized queries) and simplifying the codebase.
If you want to take a look at what I've played around with, check my work branch out. Keep in mind it's really WIP, nothing compiles or anything.
Em sábado, 18 de outubro de 2014, Shay Rojansky [email protected]
escreveu:
@franciscojuniorhttps://github.com/franciscojunior, my idea is that if #370#370 we longer need both
modes: parameters should always be sent using the extended query protocol,
so you never need to convert parameters for integration into a string
query. #370#370 would make it
pretty easy to complete the allocation optimization here, apart from
improving performance (through binary encoding and much less parsing for
non-prepared parameterized queries) and simplifying the codebase.
I've been doing similar optimizations at work for months now. We have
similar tasks, where we write groups of integers and UTF encoded strings,
among other things, to a socket stream. The allocations and copies get out
of hand really quickly, when you really start to analyze it.
Part of the solution I've come up with is to implement our own buffered
stream (actually a buffered reader and writer pair of classes) that take
the place of BufferedStream for socket operations. These classes have
methods that allow us to write, for example, an integer directly to the
buffer with exactly one copy operation (minus the copy to the call stack,
of course).
I am currently working on a buffer pool implementation. Such a thing may
help Npgsql.
One of the problems we have in Npgsql is that we have to construct an
intermediate buffer so that we can observe its length and write it to the
command buffer. This is definitely true in the case of string data, which,
because if multibyte chars, have unpredictable byte encoded lengths. So,
you're somewhat stuck in the array encoder, but you could implement a
memory stream class that allocates its internal buffer from a pool, and
copies binary data directly to/from its buffer, and see a HUGE reduction in
byte[] allocations and discards, and copies.
If you define something like IBufferedStream, which has methods for
converting various types to/from byte[], implement that on your buffered
stream and your memory stream, all the type conversion methods could take
the IBufferedStream, rather than byte[].
You'll also want to implement your own network byte order converters, so
that you can copy integers in the correct byte order directly to/from a
byte array.
Food for thought :)
-Glen
On Sat, Oct 18, 2014 at 4:55 AM, Shay Rojansky [email protected]
wrote:
I've studied and done some preliminary work here. To be honest, the amount
of needless allocations happening inside Npgsql is staggering, since the
data conversion methods all internally allocate byte arrays and return
them, rather than simply writing out values to the stream.
A good case in point is converting an array of ints for sending to the
backend. The array binary conversion method https://github.com/npgsql/npgsql/blob/master/Npgsql/NpgsqlTypes/ArrayHandling.cs#L206
first allocates a MemoryStream. It then goes over each int, converts it to
a (newly-allocated) byte array, and copies that byte array into the
MemoryStream. As this happens, the MemoryStream may or may not reallocate
its internal buffer as it fills up. At the end of the process, .ToArray()
is executed on the MemoryStream, which again copies the MemoryStream
contents to an external array. Finally, this array is copied into our
BufferStream's buffer, to be actually written to the stream when the query
is sent.
In other words, unless I've lost count, each int is copied at least 4
times. All the needless heap allocations slows down the program
considerably as the garbage collector has to clean things up later. The
situation is less dramatic but fundamentally the same for all data types.
The solution is of course to pass the connector to all conversion
functions, and for them to write out data directly to the stream, this way
we have zero allocations and zero copies (except for the single
BufferedStream, which is necessary to cut down on I/O system calls).
I think this makes the refactor/optimization depend on #370 #370, which would eliminate
client-side binding altogether and simplify everything. @Emill https://github.com/emill, you mentioned you may be interested in this
(and you already worked on this area). Do you want to work on this (my
async work is merged), or if you're too busy I can take a look?
—
Reply to this email directly or view it on GitHub #385 (comment).
Hi Glen, good to have your thoughts on this, I've been thinking about this very thing a lot today.
I think I agree with a lot of what you say. I went in a somewhat different direction: a major gripe I have with BufferedStream is the inability to directly access a byte[], populate it at my leisure and finally send it to the socket.
Of course, the issue with this approach is that the byte[] is finite, and dumping BufferedStream means it's up to us to detect that the next value no longer fits, send the existing one and start again. After all that's what BufferedStream was supposed to solve for you in a transparent way.
The work isn't trivial - every little operation needs to check the position in the buffer (e.g. WriteInt needs to check we still have at least 4 bytes left). For UTF8 encoding .NET provides a convenient and low-level Encoder class, which allows you to do exactly this - write the UTF8 string to the buffer, splitting it if necessary and resuming seamlessly at the beginning of the next chunk.
An additional performance advantage of managing your own byte[] is that you no longer pay the method call overhead of calling Write() repeatedly to the buffer. I know it sounds weird, but this may be quite significant if you're using WriteAsync(), which if you're an async purist you must do because you never know when actual I/O will occur with BufferedStream.
I personally wouldn't wrap the byte[] in a class or have anything like an IBufferedStream - the whole point for me is to have direct access to the memory, rather than passing through function calls. I'd say let's just hold a byte[] on each connector. Bite the bullet and do the manual work of populating it ourselves and sending chunks when necessary, it will hurt a bit at first but everything will be simpler and blazingly faster. I think this is very similar in spirit to what you described.
One last point regarding whether these buffers should be pooled. I think it may be a good idea to minimize sharing stuff between our connections/connectors; it's another place where we'd have to take care of locking/synchronization (this includes a performance hit), and the buffer sizes involved (8Ks each? 32K?) seem to make it not worth the effort...
Thinking about this some more I find myself agreeing even more with your proposal, no reason not to have a class wrapping the byte[] and providing methods to write int, string or whatever. I'd leave the byte[] accessible as well just in case.
Do you have some of this already written and contributable to open source? If not I can get to work on it...
On Sat, Oct 18, 2014 at 11:43 AM, Shay Rojansky [email protected]
wrote:
Hi Glen, good to have your thoughts on this, I've been thinking about this
very thing a lot today.
I think I agree with a lot of what you say. I went in a somewhat different
direction: a major gripe I have with BufferedStream is the inability to
directly access a byte[], populate it at my leisure and finally send it to
the socket.
Of course, the issue with this approach is that the byte[] is finite, and
dumping BufferedStream means it's up to us to detect that the next value no
longer fits, send the existing one and start again. After all that's what
BufferedStream was supposed to solve for you in a transparent way.
An additional performance advantage of managing your own byte[] is that
you no longer pay the method call overhead of calling Write() repeatedly to
the buffer. I know it sounds weird, but this may be quite significant if
you're using WriteAsync(), which if you're an async purist you must do
because you never know when actual I/O will occur with BufferedStream.
I personally wouldn't wrap the byte[] in a class or have anything like an
IBufferedStream - the whole point for me is to have direct access to the
memory, rather than passing through function calls. I'd say let's just hold
a byte[] on each connector. Bite the bullet and do the manual work of
populating it ourselves and sending chunks when necessary, it will hurt a
bit at first but everything will be simpler and blazingly faster. I think
this is very similar in spirit to what you described.
One last point regarding whether these buffers should be pooled. I think
it may be a good idea to minimize sharing stuff between our
connections/connectors; it's another place where we'd have to take care of
locking/synchronization (this includes a performance hit), and the buffer
sizes involved (8Ks each? 32K?) seem to make it not worth the effort...
—
Reply to this email directly or view it on GitHub #385 (comment).
I won't go quite so far as to say it's trivial, but managing a buffered
stream is actually quite easy. However, BufferedStream's implementation is
fairly involved, and I don't recommend doing it that way. Using one buffer
for read, and one for write, makes it easy, hence my reader/writer
approach. That doubles the memory footprint to 16K for a connection, but I
think that's acceptable here.
I would not leave the internal buffers publicly available, per se. I've
been thinking about this lately, too. Instead, consider a class that
exposes an interface similar to byte[], which serves access to a specific
portion of the internal buffer. A caller can ask for access to the end of
the buffer for x bytes, receive an object that enforces the bounds they ask
for, and mark that part of the buffer as used up. That way it becomes very
hard to write code that screws the buffer up.
I haven't started this in open source. You just need a method in the
writer that makes sure x bytes are left in the buffer, and if it's not,
call the underlying stream's Write method and mark the buffer write offset
to zero. For the reader, it's basically the reverse, There's very little
actual code to write. Read/write operations that exceed the buffer's
length go directly to the underlying stream.
-Glen
On Sat, Oct 18, 2014 at 11:52 AM, Glen Parker [email protected] wrote:
I won't go
On Sat, Oct 18, 2014 at 11:43 AM, Shay Rojansky [email protected]
wrote:
Hi Glen, good to have your thoughts on this, I've been thinking about
this very thing a lot today.
I think I agree with a lot of what you say. I went in a somewhat
different direction: a major gripe I have with BufferedStream is the
inability to directly access a byte[], populate it at my leisure and
finally send it to the socket.
Of course, the issue with this approach is that the byte[] is finite, and
dumping BufferedStream means it's up to us to detect that the next value no
longer fits, send the existing one and start again. After all that's what
BufferedStream was supposed to solve for you in a transparent way.
An additional performance advantage of managing your own byte[] is that
you no longer pay the method call overhead of calling Write() repeatedly to
the buffer. I know it sounds weird, but this may be quite significant if
you're using WriteAsync(), which if you're an async purist you must do
because you never know when actual I/O will occur with BufferedStream.
I personally wouldn't wrap the byte[] in a class or have anything like an
IBufferedStream - the whole point for me is to have direct access to the
memory, rather than passing through function calls. I'd say let's just hold
a byte[] on each connector. Bite the bullet and do the manual work of
populating it ourselves and sending chunks when necessary, it will hurt a
bit at first but everything will be simpler and blazingly faster. I think
this is very similar in spirit to what you described.
One last point regarding whether these buffers should be pooled. I think
it may be a good idea to minimize sharing stuff between our
connections/connectors; it's another place where we'd have to take care of
locking/synchronization (this includes a performance hit), and the buffer
sizes involved (8Ks each? 32K?) seem to make it not worth the effort...
—
Reply to this email directly or view it on GitHub #385 (comment).
I'm pretty much convinced... Leaving the buffer open or not doesn't seem terribly important, I'd definitely agree to keep it private unless there's a very good reason to do otherwise.
One point though: you say:
Read/write operations that exceed the buffer's length go directly to the underlying stream
It seems like once we exceed the buffer length we should write to the underlying stream, but then continue inside the buffer, this way a big message gets split several times (inside the same buffer obviously). I'm guessing this is what you meant...
An optimization that comes to mind for byte-array inputs: for big ones it may be more efficient to write whatever accumulated in the buffer, and then simply write out the buffer directly.
I'll work on this in the coming days, will share once I have something workable.
Type handlers are loaded by reflecting on the Npgsql assembly.
Great! I think this would help to achieve a very old idea: enable users to install custom datatype handlers. I think your change to load handlers by reflection could be used to load custom handlers from user provided assemblies.
That's a great idea, I didn't know you discussed this before... I think the new system, with a clear class and API for type handlers would definitely make it easier to add external ones. We'd still have to think about how the user registers these, we can add this a bit later as we see that the type handler API stabilizes etc...
Started to introduce Code Contracts to help us improve our code quality.
Great! I saw those contract lines in your branch. I'll study them to get more familiarized with Contracts.
this is a dependency for contributing I recon? So if a person wants to contribute, to be able to compile the lib should be installed I guess, perhaps a good idea to put the link to that lib somewhere so people who want to contribute don't need to look for it. (I never used it, so if it ships with vs.net, then scratch that remark ;))
Actually code contract isn't an additional dependency - the calls are in the System.Diagnostics namespace in .NET itself. To actually have the contracts enforced, though, you do need to download the code contract package, but you definitely don't need it to compile. I also took care not to depend on code contracts in any way in the release build, only in debug, so at least right now it's just a technology that should help us detect coding problems when running our tests etc. It definitely already helped me while doing this rewrite - I really recommend it to anyone who doesn't know it!
Regarding the non-sequential caching of mutable values, I'll try to explain better... Say you have a row with a bytea blob. When in non-sequential mode, the first time that the value is fetched, NpgsqlDataReader will cache it internally so that if that same value is requested again, we return the cache. @FransBouma, it's no about scanning or comparing two different columns for equiality, just about returning the same column in the same row more than once. I have a commented-out line in a test that checks exactly for this - it may make situation clearer (note I removed this line in the latest commits).
The reason we want to cache, is that even though we have the entire row in memory (in non-sequential mode), decoding it can be expensive (think UTF8, text-encoded bytea...), and it seems like NpgsqlDataReader.GetValue() should really return immediately on values that have already been read.
@FransBouma, I also don't feel amazing about users modifying cached values like this, but the alternative (handing out copies) seems to kill the whole point of caching, and harm performance... So I'm leaning towards allowing the modification of the cached value, but I'd definitely feel much better if there were docs supporting that. I'll try testing how SqlClient behaves in this regard.
While checking the msdn documentation, I think that for the bytea and arrays datatypes, we could make something like sqldatareader. They have the GetBytes method which accept a byte[] where we would copy the bytes to. And also have the GetSqlBytes which returns an SqlBytes object which contains the bytes of the data.
We could make the same. GetBytes would receive a buffer where we would copy the bytes from the bytea column and also we could create a NpgsqlBytea datatype where it would hold "the cached value within Npgsql". SqlBytes have the Stream and Value properties which could be used by users to have access to the data as stream or a copy of the bytes which would solve the problem of the cache copy. (If the user really wants a copy she would pay the performance price).
I'm not sure I understand 100%, but we do implement GetBytes() and even the new .NET 4.5 GetStream() methods. These are totally safe, because as you say we copy data into a user-provided array. What's problematic specifically is what we return when GetValue() is called - a copy of the cached value or the cached value itself...
I think that for arrays it's even worse: it's difficult to imagine an API which would fill user-provided arrays (and in any case we have to decide what happens with GetValue()). The same problem happens again with bit strings, or any other mutable thing we return from NpgsqlDataReader...
Yeah, that's really exciting :) I guess we should reach out to them and understand what that means exactly, and coordinate our efforts? Should I do it or is anyone particularly interested?
Just pushed another commit that implements bit strings. This involved a bit of refactoring of the type handling system to support the case where BIT(1) is returned as bool, whereas other bit types are returned as bit strings (see #362). See tests in Types/BitStringTests.cs.
In #335, I asked why use the custom Npgsql BitString class to represent bitstrings, rather than .NET BitArray. It's an old class, and I mistakenly thought it didn't support access without going through object, which would imply boxing/unboxing. That actually isn't true - you can access it just fine, you just can't enumerate it without boxing/unboxing (but you can do an efficient for loop). So for now I implemented around the .NET BitArray class. If anyone can see any issue with it please let me know, I can easily go back to Npgsql's BitString (@hackcraft, especially interested in what you have to say).
Also note that bitstring text decoding used to handle hexadecimal format, and even a mixing of binary and hexadecimal in the same value... I searched and couldn't find anything, as far as I can tell PostgreSQL only sends back a string of ones and zeros.
Type handlers are loaded by reflecting on the Npgsql assembly.
Great! I think this would help to achieve a very old idea: enable users to install custom datatype handlers. I think your change to load handlers by reflection could be used to load custom handlers from user provided assemblies.
That's a great idea, I didn't know you discussed this before... I think the new system, with a clear class and API for type handlers would definitely make it easier to add external ones. We'd still have to think about how the user registers these, we can add this a bit later as we see that the type handler API stabilizes etc...
Yes, this was a long time ago. I was thinkingabout adding support for user defined types. The idea would be to add support for custom type handlers. As you said, I think we can add this support later when the handler api stabilizes.
Started to introduce Code Contracts to help us improve our code quality.
Great! I saw those contract lines in your branch. I'll study them to get more familiarized with Contracts.
this is a dependency for contributing I recon? So if a person wants to contribute, to be able to compile the lib should be installed I guess, perhaps a good idea to put the link to that lib somewhere so people who want to contribute don't need to look for it. (I never used it, so if it ships with vs.net, then scratch that remark ;))
Actually code contract isn't an additional dependency - the calls are in the System.Diagnostics namespace in .NET itself. To actually have the contracts enforced, though, you do need to download the code contract package, but you definitely don't need it to compile. I also took care not to depend on code contracts in any way in the release build, only in debug, so at least right now it's just a technology that should help us detect coding problems when running our tests etc. It definitely already helped me while doing this rewrite - I really recommend it to anyone who doesn't know it!
Regarding the non-sequential caching of mutable values, I'll try to explain better... Say you have a row with a bytea blob. When in non-sequential mode, the first time that the value is fetched, NpgsqlDataReader will cache it internally so that if that same value is requested again, we return the cache. @FransBouma, it's no about scanning or comparing two different columns for equiality, just about returning the same column in the same row more than once. I have a commented-out line in a test that checks exactly for this - it may make situation clearer (note I removed this line in the latest commits).
The reason we want to cache, is that even though we have the entire row in memory (in non-sequential mode), decoding it can be expensive (think UTF8, text-encoded bytea...), and it seems like NpgsqlDataReader.GetValue() should really return immediately on values that have already been read.
@FransBouma, I also don't feel amazing about users modifying cached values like this, but the alternative (handing out copies) seems to kill the whole point of caching, and harm performance... So I'm leaning towards allowing the modification of the cached value, but I'd definitely feel much better if there were docs supporting that. I'll try testing how SqlClient behaves in this regard.
While checking the msdn documentation, I think that for the bytea and arrays datatypes, we could make something like sqldatareader. They have the GetBytes method which accept a byte[] where we would copy the bytes to. And also have the GetSqlBytes which returns an SqlBytes object which contains the bytes of the data.
We could make the same. GetBytes would receive a buffer where we would copy the bytes from the bytea column and also we could create a NpgsqlBytea datatype where it would hold "the cached value within Npgsql". SqlBytes have the Stream and Value properties which could be used by users to have access to the data as stream or a copy of the bytes which would solve the problem of the cache copy. (If the user really wants a copy she would pay the performance price).
I'm not sure I understand 100%, but we do implement GetBytes() and even the new .NET 4.5 GetStream() methods. These are totally safe, because as you say we copy data into a user-provided array. What's problematic specifically is what we return when GetValue() is called - a copy of the cached value or the cached value itself...
Ah, OK. I was thinking about the specific provider get* methods. Indeed in the case of getvalue I think we would need to check if it OK to hurt the performance by copying the value.
If I'm not wrong, sqlclient documentation says that by using the specific provider methods you get a better performance. I think this is the case because getvalue would make this copy while the specific provider method wouldn't.
I think that for arrays it's even worse: it's difficult to imagine an API which would fill user-provided arrays (and in any case we have to decide what happens with GetValue()). The same problem happens again with bit strings, or any other mutable thing we return from NpgsqlDataReader...
I see. In the case of the bitstring, we could encapsulate the data inside a Npgsqlbitstring object for example which wouldn't allow the data to be changed directly. Similar to sqlbytes for example. If the user wants to make changes to the data, she can request a copy to this object and work with it.
Maybe I'm saying too much nonsense things. I'm thinking about deferring the need to make a copy of the data until strictly necessary and if the user needs it. In the 95% of the use case, I think the user won't need to make changes and the flow with better performance would be used ( return the data without making copies. )
Yeah, that's really exciting :) I guess we should reach out to them and understand what that means exactly, and coordinate our efforts? Should I do it or is anyone particularly interested?
For me it is OK if you contact them to check what they have in mind about it. I'm looking forward to hear good news. :-)
Ah, OK. I was thinking about the specific provider get* methods. Indeed in the case of getvalue I think we would need to check if it OK to hurt the performance by copying the value.
If I'm not wrong, sqlclient documentation says that by using the specific provider methods you get a better performance. I think this is the case because getvalue would make this copy while the specific provider method wouldn't.
I saw that in the docs too. I think it's less about caching, and more about the extra conversion step from the provider-specific type (which they always go through) to the normal .NET type. For example, the date they receive from SQLServer is a special date ("provider-specific") - if you want a .NET DateTime they need to do an extra conversion, and this is why it's less efficient (probably not the caching, although I'm not sure). Npgsql has the same behavior with date/time types, although it really doesn't seem like a big deal to me.
I see. In the case of the bitstring, we could encapsulate the data inside a Npgsqlbitstring object for example which wouldn't allow the data to be changed directly. Similar to sqlbytes for example. If the user wants to make changes to the data, she can request a copy to this object and work with it.
Maybe I'm saying too much nonsense things. I'm thinking about deferring the need to make a copy of the data until strictly necessary and if the user needs it. In the 95% of the use case, I think the user won't need to make changes and the flow with better performance would be used ( return the data without making copies. )
It's a difficult problem. The approach of a special immutable type doesn't work well for arrays - I think we don't want to push a special array wrapper type just for this... And in a way the same is true for bitstrings - .NET has a standard BitArray type that's natural for returning BitStrings, forcing users to work with some other type just for immutability seems problematic...
I'm not sure what the solution should be here, I'm leaning to returning the cached version for performance and clearly documenting it...
Yeah, that's really exciting :) I guess we should reach out to them and understand what that means exactly, and coordinate our efforts? Should I do it or is anyone particularly interested?
For me it is OK if you contact them to check what they have in mind about it. I'm looking forward to hear good news. :-)
I saw that in the docs too. I think it's less about caching, and more about the extra conversion step from the provider-specific type (which they always go through) to the normal .NET type. For example, the date they receive from SQLServer is a special date ("provider-specific") - if you want a .NET DateTime they need to do an extra conversion, and this is why it's less efficient (probably not the caching, although I'm not sure). Npgsql has the same behavior with date/time types, although it really doesn't seem like a big deal to me.
Yes, you are right. I was thinking that maybe they were having some copying under covers happening too which would imply in performance penalties too, besides the data conversion.
I'm not sure what the solution should be here, I'm leaning to returning the cached version for performance and clearly documenting it...
This is more or less done. There are some specific areas that need work but overall we now have an efficient, allocate-once solution for most data types etc. Specific problems/tasks can be treated in other issues.
Activity
[-]Remove allocations from parameter read/write process[/-][+]Remove allocations from parameter read/write values[/+][-]Remove allocations from parameter read/write values[/-][+]Remove allocations from data read/write operations[/+]roji commentedon Oct 18, 2014
I've studied and done some preliminary work here. To be honest, the amount of needless allocations happening inside Npgsql is staggering, since the data conversion methods all internally allocate byte arrays and return them, rather than simply writing out values to the stream.
A good case in point is converting an array of ints for sending to the backend. The array binary conversion method first allocates a MemoryStream. It then goes over each int, converts it to a (newly-allocated) byte array, and copies that byte array into the MemoryStream. As this happens, the MemoryStream may or may not reallocate its internal buffer as it fills up. At the end of the process, .ToArray() is executed on the MemoryStream, which again copies the MemoryStream contents to an external array. Finally, this array is copied into our BufferStream's buffer, to be actually written to the stream when the query is sent.
In other words, unless I've lost count, each int is copied at least 4 times. Besides the needless copying itself, all the heap allocations slows down the program considerably as the garbage collector has to clean things up later. The situation is less dramatic but fundamentally the same for all data types.
The solution is of course to pass the connector to all conversion functions, and for them to write out data directly to the stream, this way we have zero allocations and zero copies (except for the single BufferedStream, which is necessary to cut down on I/O system calls).
I've begun to do this, but am being blocked by one thing: our non-prepared parameterized query support. As part of client-side binding, the conversion methods must be called in a way that produces simple strings, which will get integrated into the query text. It will be difficult to architecture the code to support both modes (direct-to-stream and string-producing).
I think this makes the refactor/optimization depend on #370, which would eliminate client-side binding altogether and simplify everything. @Emill, you mentioned you may be interested in this (and you already worked on this area). Do you want to work on this (my async work is merged), or if you're too busy I can take a look?
franciscojunior commentedon Oct 18, 2014
Yes. I think this is one of the biggest performance blocker of Npgsql. We will get a huge performance improvement when we remove all those allocations. Also, they impose a big hit on garbage collector.
:( :(
Hmmm, I see. In order to support both modes we would have duplicated code: one writing directly to the stream and another returning a byte[].
@roji , is the branch you are working on this public? If possible, I'd like to have a look at it, please. Maybe there is something I can help you with.
roji commentedon Oct 18, 2014
@franciscojunior, my idea is that if #370 we no longer need both modes: parameters should always be sent using the extended query protocol, so you never need to convert parameters for integration into a string query. #370 would make it pretty easy to complete the allocation optimization here, apart from improving performance (through binary encoding and much less parsing for non-prepared parameterized queries) and simplifying the codebase.
If you want to take a look at what I've played around with, check my work branch out. Keep in mind it's really WIP, nothing compiles or anything.
franciscojunior commentedon Oct 18, 2014
Em sábado, 18 de outubro de 2014, Shay Rojansky [email protected]
escreveu:
Great! Let's get #370 implemented! :-)
If you want to take a look at what I've played around with, check my work
Thanks! I'll have a look at it. I hope I can help you with something.
Regards,
Francisco Figueiredo Jr.
Npgsql Lead Developer
http://www.npgsql.org
http://gplus.to/franciscojunior
http://fxjr.blogspot.com
http://twitter.com/franciscojunior
glenebob commentedon Oct 18, 2014
Hi all,
I've been doing similar optimizations at work for months now. We have
similar tasks, where we write groups of integers and UTF encoded strings,
among other things, to a socket stream. The allocations and copies get out
of hand really quickly, when you really start to analyze it.
Part of the solution I've come up with is to implement our own buffered
stream (actually a buffered reader and writer pair of classes) that take
the place of BufferedStream for socket operations. These classes have
methods that allow us to write, for example, an integer directly to the
buffer with exactly one copy operation (minus the copy to the call stack,
of course).
I am currently working on a buffer pool implementation. Such a thing may
help Npgsql.
One of the problems we have in Npgsql is that we have to construct an
intermediate buffer so that we can observe its length and write it to the
command buffer. This is definitely true in the case of string data, which,
because if multibyte chars, have unpredictable byte encoded lengths. So,
you're somewhat stuck in the array encoder, but you could implement a
memory stream class that allocates its internal buffer from a pool, and
copies binary data directly to/from its buffer, and see a HUGE reduction in
byte[] allocations and discards, and copies.
If you define something like IBufferedStream, which has methods for
converting various types to/from byte[], implement that on your buffered
stream and your memory stream, all the type conversion methods could take
the IBufferedStream, rather than byte[].
You'll also want to implement your own network byte order converters, so
that you can copy integers in the correct byte order directly to/from a
byte array.
Food for thought :)
-Glen
On Sat, Oct 18, 2014 at 4:55 AM, Shay Rojansky [email protected]
wrote:
roji commentedon Oct 18, 2014
Hi Glen, good to have your thoughts on this, I've been thinking about this very thing a lot today.
I think I agree with a lot of what you say. I went in a somewhat different direction: a major gripe I have with BufferedStream is the inability to directly access a byte[], populate it at my leisure and finally send it to the socket.
Of course, the issue with this approach is that the byte[] is finite, and dumping BufferedStream means it's up to us to detect that the next value no longer fits, send the existing one and start again. After all that's what BufferedStream was supposed to solve for you in a transparent way.
The work isn't trivial - every little operation needs to check the position in the buffer (e.g. WriteInt needs to check we still have at least 4 bytes left). For UTF8 encoding .NET provides a convenient and low-level Encoder class, which allows you to do exactly this - write the UTF8 string to the buffer, splitting it if necessary and resuming seamlessly at the beginning of the next chunk.
An additional performance advantage of managing your own byte[] is that you no longer pay the method call overhead of calling Write() repeatedly to the buffer. I know it sounds weird, but this may be quite significant if you're using WriteAsync(), which if you're an async purist you must do because you never know when actual I/O will occur with BufferedStream.
I personally wouldn't wrap the byte[] in a class or have anything like an IBufferedStream - the whole point for me is to have direct access to the memory, rather than passing through function calls. I'd say let's just hold a byte[] on each connector. Bite the bullet and do the manual work of populating it ourselves and sending chunks when necessary, it will hurt a bit at first but everything will be simpler and blazingly faster. I think this is very similar in spirit to what you described.
One last point regarding whether these buffers should be pooled. I think it may be a good idea to minimize sharing stuff between our connections/connectors; it's another place where we'd have to take care of locking/synchronization (this includes a performance hit), and the buffer sizes involved (8Ks each? 32K?) seem to make it not worth the effort...
roji commentedon Oct 18, 2014
Thinking about this some more I find myself agreeing even more with your proposal, no reason not to have a class wrapping the byte[] and providing methods to write int, string or whatever. I'd leave the byte[] accessible as well just in case.
Do you have some of this already written and contributable to open source? If not I can get to work on it...
glenebob commentedon Oct 18, 2014
I won't go
On Sat, Oct 18, 2014 at 11:43 AM, Shay Rojansky [email protected]
wrote:
glenebob commentedon Oct 18, 2014
Woops...
I won't go quite so far as to say it's trivial, but managing a buffered
stream is actually quite easy. However, BufferedStream's implementation is
fairly involved, and I don't recommend doing it that way. Using one buffer
for read, and one for write, makes it easy, hence my reader/writer
approach. That doubles the memory footprint to 16K for a connection, but I
think that's acceptable here.
I would not leave the internal buffers publicly available, per se. I've
been thinking about this lately, too. Instead, consider a class that
exposes an interface similar to byte[], which serves access to a specific
portion of the internal buffer. A caller can ask for access to the end of
the buffer for x bytes, receive an object that enforces the bounds they ask
for, and mark that part of the buffer as used up. That way it becomes very
hard to write code that screws the buffer up.
I haven't started this in open source. You just need a method in the
writer that makes sure x bytes are left in the buffer, and if it's not,
call the underlying stream's Write method and mark the buffer write offset
to zero. For the reader, it's basically the reverse, There's very little
actual code to write. Read/write operations that exceed the buffer's
length go directly to the underlying stream.
-Glen
On Sat, Oct 18, 2014 at 11:52 AM, Glen Parker [email protected] wrote:
roji commentedon Oct 18, 2014
I'm pretty much convinced... Leaving the buffer open or not doesn't seem terribly important, I'd definitely agree to keep it private unless there's a very good reason to do otherwise.
One point though: you say:
It seems like once we exceed the buffer length we should write to the underlying stream, but then continue inside the buffer, this way a big message gets split several times (inside the same buffer obviously). I'm guessing this is what you meant...
An optimization that comes to mind for byte-array inputs: for big ones it may be more efficient to write whatever accumulated in the buffer, and then simply write out the buffer directly.
I'll work on this in the coming days, will share once I have something workable.
131 remaining items
roji commentedon Dec 20, 2014
@franciscojunior:
That's a great idea, I didn't know you discussed this before... I think the new system, with a clear class and API for type handlers would definitely make it easier to add external ones. We'd still have to think about how the user registers these, we can add this a bit later as we see that the type handler API stabilizes etc...
@FransBouma:
Actually code contract isn't an additional dependency - the calls are in the System.Diagnostics namespace in .NET itself. To actually have the contracts enforced, though, you do need to download the code contract package, but you definitely don't need it to compile. I also took care not to depend on code contracts in any way in the release build, only in debug, so at least right now it's just a technology that should help us detect coding problems when running our tests etc. It definitely already helped me while doing this rewrite - I really recommend it to anyone who doesn't know it!
Regarding the non-sequential caching of mutable values, I'll try to explain better... Say you have a row with a bytea blob. When in non-sequential mode, the first time that the value is fetched, NpgsqlDataReader will cache it internally so that if that same value is requested again, we return the cache. @FransBouma, it's no about scanning or comparing two different columns for equiality, just about returning the same column in the same row more than once. I have a commented-out line in a test that checks exactly for this - it may make situation clearer (note I removed this line in the latest commits).
The reason we want to cache, is that even though we have the entire row in memory (in non-sequential mode), decoding it can be expensive (think UTF8, text-encoded bytea...), and it seems like NpgsqlDataReader.GetValue() should really return immediately on values that have already been read.
@FransBouma, I also don't feel amazing about users modifying cached values like this, but the alternative (handing out copies) seems to kill the whole point of caching, and harm performance... So I'm leaning towards allowing the modification of the cached value, but I'd definitely feel much better if there were docs supporting that. I'll try testing how SqlClient behaves in this regard.
@franciscojunior, regarding your suggestion on this:
I'm not sure I understand 100%, but we do implement GetBytes() and even the new .NET 4.5 GetStream() methods. These are totally safe, because as you say we copy data into a user-provided array. What's problematic specifically is what we return when GetValue() is called - a copy of the cached value or the cached value itself...
I think that for arrays it's even worse: it's difficult to imagine an API which would fill user-provided arrays (and in any case we have to decide what happens with GetValue()). The same problem happens again with bit strings, or any other mutable thing we return from NpgsqlDataReader...
Yeah, that's really exciting :) I guess we should reach out to them and understand what that means exactly, and coordinate our efforts? Should I do it or is anyone particularly interested?
roji commentedon Dec 20, 2014
Just pushed another commit that implements bit strings. This involved a bit of refactoring of the type handling system to support the case where BIT(1) is returned as bool, whereas other bit types are returned as bit strings (see #362). See tests in Types/BitStringTests.cs.
In #335, I asked why use the custom Npgsql BitString class to represent bitstrings, rather than .NET BitArray. It's an old class, and I mistakenly thought it didn't support access without going through object, which would imply boxing/unboxing. That actually isn't true - you can access it just fine, you just can't enumerate it without boxing/unboxing (but you can do an efficient for loop). So for now I implemented around the .NET BitArray class. If anyone can see any issue with it please let me know, I can easily go back to Npgsql's BitString (@hackcraft, especially interested in what you have to say).
Also note that bitstring text decoding used to handle hexadecimal format, and even a mixing of binary and hexadecimal in the same value... I searched and couldn't find anything, as far as I can tell PostgreSQL only sends back a string of ones and zeros.
franciscojunior commentedon Dec 21, 2014
Yes, this was a long time ago. I was thinkingabout adding support for user defined types. The idea would be to add support for custom type handlers. As you said, I think we can add this support later when the handler api stabilizes.
Ah, OK. I was thinking about the specific provider get* methods. Indeed in the case of getvalue I think we would need to check if it OK to hurt the performance by copying the value.
If I'm not wrong, sqlclient documentation says that by using the specific provider methods you get a better performance. I think this is the case because getvalue would make this copy while the specific provider method wouldn't.
I see. In the case of the bitstring, we could encapsulate the data inside a Npgsqlbitstring object for example which wouldn't allow the data to be changed directly. Similar to sqlbytes for example. If the user wants to make changes to the data, she can request a copy to this object and work with it.
Maybe I'm saying too much nonsense things. I'm thinking about deferring the need to make a copy of the data until strictly necessary and if the user needs it. In the 95% of the use case, I think the user won't need to make changes and the flow with better performance would be used ( return the data without making copies. )
For me it is OK if you contact them to check what they have in mind about it. I'm looking forward to hear good news. :-)
roji commentedon Dec 21, 2014
@franciscojunior, regarding the caching:
I saw that in the docs too. I think it's less about caching, and more about the extra conversion step from the provider-specific type (which they always go through) to the normal .NET type. For example, the date they receive from SQLServer is a special date ("provider-specific") - if you want a .NET DateTime they need to do an extra conversion, and this is why it's less efficient (probably not the caching, although I'm not sure). Npgsql has the same behavior with date/time types, although it really doesn't seem like a big deal to me.
It's a difficult problem. The approach of a special immutable type doesn't work well for arrays - I think we don't want to push a special array wrapper type just for this... And in a way the same is true for bitstrings - .NET has a standard BitArray type that's natural for returning BitStrings, forcing users to work with some other type just for immutability seems problematic...
I'm not sure what the solution should be here, I'm leaning to returning the cached version for performance and clearly documenting it...
OK great, I'll write them and update you guys!
franciscojunior commentedon Dec 24, 2014
Yes, you are right. I was thinking that maybe they were having some copying under covers happening too which would imply in performance penalties too, besides the data conversion.
Agreed. +1 for this.
Thanks for having a look at this.
roji commentedon Feb 16, 2015
This is more or less done. There are some specific areas that need work but overall we now have an efficient, allocate-once solution for most data types etc. Specific problems/tasks can be treated in other issues.