Repository navigation
Conversation
Add abstract base class NpgsqlStream and subclasses NpgsqlBufferedStream and NpgsqlMemoryStream. Change NpgsqlConnector to do all backend IO through NpgsqlBufferedStream. Use NpgsqlMemoryStream for binary array formatting. In Connector.SendCopyInDone(), add a Flush() call; without it, the test failed.
|
Continuation of discussion in #385 |
Add string read/write support, with null-terminator support. Remove the EnsureWriteBufferSpace##() methods, not worth it. Change all the numeric Write() methods to WriteType(). Use NpgsqlMemoryStream in the query re-write methods.
Change binary back to native converters to operate on the backend stream directly. Fix busted NpgsqlStream.ReadInt64() and ReadUInt64(). Add NpgsqlStream.ReadExact(), which does not return until all requested bytes have been copied. Add NpgsqlStream.Skip() which reads and skips bytes without copying to an outside buffer.
There was a problem hiding this comment.
The idea of passing the size of the string being written here is optimization?
|
Awesome job, @glenebob ! |
|
Thanks Francisco :) Yes, the length is optimization. That way the stream never has to call -Glen On Mon, Oct 20, 2014 at 9:29 AM, Francisco Figueiredo Jr. <
|
You are welcome, Glen! You rock!
Great! |
|
This really is starting to look like a great optimization for Npgsql. One note (which I also mentioned in #385): rather than requiring us to manually specify the length when invoking WriteString, we could have a separate WriteAsciiString, which simply assumes that the string given is ASCII-only, i.e. that its character length and its encoded byte length will be equal. This would prevent errors when someone changes the string but forgets to update the manual length parameter (5 above). |
There was a problem hiding this comment.
Typo :) I'll fix it.
I won't be of any use on this until the weekend, but I have a couple additional ideas to try before it gets merged.
-Glen
|
@glenebob, some comments. First, as mentioned elsewhere the idea of passing in the length of strings seems extremely error-prone, I think it's much better to simply have another method (WriteAsciiString) which internally uses Length. Second, if I understood things, NpgsqlMemoryStream is mainly for the case of non-prepared parameterized queries (i.e. where we actually rewrite the query text). In #370 we discussed switching to the extended protocol for this, meaning we don't need to rewrite the query text anymore (apart from $ to indicate the parameters). So it may not make sense to invest much in this area... As a workaround until #370 is done, we can simply have NpgsqlBufferedStream wrap a .NET MemoryStream. I also see that NpgsqlMemoryStream is used by NpgsqlBufferedStream, in ReadString(), but I'm not sure what value it provides there over the built-in MemoryStream... In general, while I absolutely see the sense of NpgsqlBufferedStream I don't really see what NpgsqlMemoryStream brings to the table yet... One more note on that: if we only have NpgsqlBufferedStream and no NpgsqlMemoryStream, we no longer have a virtual class hierarchy (e.g. virtual ReadInt) and it's another small performance gain. But maybe I'm exaggerating at this point. |
|
Some more:
I have a few other tweaks I'd do but nothing very important, I'll wait around until you finish your good work @glenebob. |
|
On Fri, Oct 24, 2014 at 1:11 AM, Shay Rojansky [email protected]
MemoryStream is used in ReadString() and WriteString(), and in the query
-Glen
|
OK, I'll hold off on this until we see where it goes. But I have a strong suspicion that once we start writing directly to the NpgsqlBufferedStream, and stop (seriously) rewriting query text in the non-prepared parameterized query case, there won't really be any use case left for our own optimized NpgsqlMemoryStream (NpgsqlBufferedStream will be all we'll need). Let's wait and see.
Yeah OK, I felt kind of shitty writing that but I was in the mood :) Forget about it :) |
Add support for length-prefixed strings. Add support for substring IO. Clean up the string IO interface so it's a bit more intuitive (I hope). Migrate the query re-write code use the substring IO support. Use NpgsqlStream.CopyTo() to more efficiently copy a query buffer to the transport stream. Remove some unused and obsolete methods from PGUtil.
|
I just pushed up another commit to the stream PR. On Fri, Oct 24, 2014 at 11:04 AM, Shay Rojansky [email protected]
For simple queries, we definitely have to construct the query buffer ahead This costs us a fair amount of GC overhead, because each simply query -Glen |
|
Looking into what SqlClient is doing, they too use a pool, see http://referencesource.microsoft.com/#System.Data/data/System/Data/SqlClient/TdsParserSessionPool.cs which is used to pool tds state objects (which contain the tds parser for the tds protocol messages to communicate with the parser), which is e.g. used in SqlCommand.RunExecuteReaderTds (http://referencesource.microsoft.com/#System.Data/data/System/Data/SqlClient/SqlCommand.cs#2843) . That code isn't the cleanest/easiest on the eyes, you've been warned ;) So if MS uses a pool, with a message based protocol system, I think a pool with buffer objects is indeed the best way forward. Not sure how low-level it should be though, they use a state object with a buffer and a protocol parser together, which might be something fitting their specific situation.
|
|
Den 26 okt 2014 06:59 skrev "Glen Parker" [email protected]:
Why? If we know the length of the query (GetByteCount), we can calculate
|
I agree with @Emill here. First, whether the query is simple or not, if its GetMaxByteCount() fits within our buffer then we can encode directly into our BufferStream, then go back and fill in the actual length. This should be the case in 95% percent of cases (depending on our buffer size). The only interesting case is when the entire buffer size isn't enough to hold GetMaxByteCount(). Here we have two options:
My gut says we should at least hold off on the second option for now - we can always optimize more later. It's hard to know whether the addition of a pool only for strings larger than the configured buffer is worthwhile: we can simply instruct users to configure their connection's buffer size to correspond to their expected string sizes, and take a small processing hit otherwise. Let me know when I can get to work @glenebob :) |
|
@FransBouma, regarding your comment:
The pool you're referring to appears to be a very specific pool for TDS session objects - I'm not familiar enough with TDS and SqlClient to know exactly what that refers to. The discussion above is a bit more on lower-level problems such as writing/encoding data and strings, although you're absolutely right we should be looking at eliminating allocations in other areas of Npgsql (through pools or otherwise). For example, regardless of all the work we're doing here, Npgsql internally allocates a new NpgsqlRow for each row it reads - definitely not good. I'm not sure a pool is needed to deal with that - why not just have a single row object on the connector and repopulate it every time someone reads. |
One thing to note: currently npgsql does boxing/unboxing of values, which is slow compared to using a native type from bytes. I didn't know how slow till I wrote the rawbenchmark system for various ORMs and had my baseline datareader wrapper simply utilize GetValues(). So to me, e.g. reader.GetInt32(ordinal) should directly convert the bytes from the raw buffer received from the server into an int, and return it, without any conversion to object. Valueable performance is lost if boxing/unboxing is done, as these code paths get very hot during resultset reading. |
I suggest the first method. However, since Encoder.Convert() doesn't accept strings, I wrote an own version, see https://gist.github.com/Emill/4aaf27cd4d0b7b3f933f.
This way we make no allocations at all. I did some benchmarks on this and it is faster than .GetBytes(string) for small strings (since we mostly only need one pass). For larger strings, it takes about equal time as .GetBytes(string), but with the good thing that no allocation of a byte[] has to be done. |
You're absolutely right. I'm under the impression that under the ADO.NET contract the row is only supposed to stay alive until DbDataReader.Next() is called, and then it can be thrown away. But the row size is indeed an important factor, I hope we can make it work.
True again, this has long bothered me - boxing/unboxing is pretty awful. I think that after the current work phase (which is a bit more write-centric) we'll take a long hard look at how the row handling and reading is managed. Thanks for your inputs on this, I agree with everything. |
SqlClient uses an interesting approach: http://referencesource.microsoft.com/#System.Data/data/System/Data/SqlClient/SqlBuffer.cs#85 |
|
I've done this kind of thing in C, but I'm pretty sure that in C# in order to read the struct from the byte array you need to be in unsafe mode... That's one advantage the Microsoft classes have over Npgsql. But maybe I'm wrong on requiring unsafe for that. |
|
SqlClient's approach is actually "safe", at least according to http://graphicdna.blogspot.se/2014/03/fast-casting-of-c-structs-with-no.html. It's not about casting a byte[] to a struct. It is about using a "union" type in C#. |
|
Although what about types like byte[] and string which are reference types... |
|
Am working on this and some general cleanup and I've run into the FastPath.cs mechanism which is a bit problematic - seems to be the only place in Npgsql where our actual NetworkStream is exposed publicly (i.e. there's a constructor that accepts it). I hope it's some sort of mistake, @franciscojunior or anyone else - any input on this? Or can I make the constructor internal/private and refactor? |
There was a problem hiding this comment.
Yes. Good catch. Thank you.
|
How is the PopulateReadBuffer supposed to work? Wouldn't it be better to put the Stream.Read call in a loop that loops until all requested bytes are read? The case "If the remote host shuts down the connection, and all available data has been received, the Read method completes immediately and return zero bytes." doesn't seem to be handled correctly everywhere in the code, such as in https://github.com/npgsql/npgsql/pull/388/files#diff-7a1d054a83dab5271bf2de0c30ca2057R287, which would make that loop infinite. |
There was a problem hiding this comment.
Wouldn't a better approach be to first write as many bytes that can be written to the writeBuffer, then flush it, and then write the remaining bytes to the beginning of the writeBuffer? That should result in fewer calls to Stream.Write in total.
|
Guys, just to let you know I'm working on this code. Haven't gone over all of the comments above but most seem correct to me... |
|
@glenebob, one quick question... I'd like to make code styling changes - private members with underscore and stuff like that - which most of the codebase uses, I wanted to check if that's alright with you. |
|
As a more general note: IMHO methods that read things (e.g. Read(byte[])) should return only after reading the entire amount of data requested, and never before. This is contrary to the behavior of .NET BufferStream, which is a much more thin wrapper than what we're trying to achieve (and this is another argument for why we need our own). |
There was a problem hiding this comment.
Isn't it better to simply do BackendEncoding.UTF8Encoding.GetByteCount/.GetBytes together with the header and null-terminator?
|
On Fri, Oct 31, 2014 at 12:53 AM, Shay Rojansky [email protected]
I added void ReadExact() to achieve this functionality. It could just as -Glen |
|
On Fri, Oct 31, 2014 at 12:43 AM, Shay Rojansky [email protected]
I'll do it. I got used to writing the way I did here at work, and forgot -Glen |
Add _ prefix to private and protected fields. Fix and optimize PopulateReadBuffer(). Make sure never to pass a direct read or write operation to the inner stream larger than BufferSize, to avoid problems with socket buffers. Remove try/catch around Encoding calls. Many bug fixes and optimizations.
e1d8c57 to
1f140e5
Compare
1236d1f to
e8ae2e0
Compare
2fc8944 to
3eb6fa4
Compare
|
Closing this as NpgsqlBuffer has now been implemented differently in Npgsql 3.0. Thanks for the invaluable discussion and attempts around this...! |
Hi all,
Per discussion with @roji, I implemented some Stream classes to replace BufferedStream and MemoryStream, and got them working in Npgsql.
This is really preliminary work, and just the start of a much bigger project that I don't have time to finish, but i think it provides part of the basis needed for Npgsql to really take control of its buffer management.
i did not implement a buffer pool, which may prove to be another important aspect of this project, but a buffer pool is really quite trivial to write, and adapting NpgsqlMemoryStream to it would also be trivial.
The hard, tedious work ahead will lie in refactoring Npgsql to extend and use these new streams to eliminate a lot more allocations and copy operations, partly by taking advantage of the fact that we can have full access to their buffers.
-Glen