Skip to content

New custom stream classes replacing BufferedStream and MemoryStream - #388

Closed
glenebob wants to merge 6 commits into
npgsql:masterfrom
glenebob:npgsql_stream
Closed

glenebob wants to merge 6 commits into
npgsql:masterfrom
glenebob:npgsql_stream

Conversation

@glenebob

Copy link
Copy Markdown
Contributor

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

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.
@roji

roji commented Oct 19, 2014

Copy link
Copy Markdown
Member

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.
Comment thread Npgsql/NpgsqlCommand.cs Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea of passing the size of the string being written here is optimization?

@franciscojunior

Copy link
Copy Markdown
Member

Awesome job, @glenebob !

@glenebob

Copy link
Copy Markdown
Contributor Author

Thanks Francisco :)

Yes, the length is optimization. That way the stream never has to call
GetByteCount() to determine if/how much to allocate ahead.

-Glen

On Mon, Oct 20, 2014 at 9:29 AM, Francisco Figueiredo Jr. <
[email protected]> wrote:

Awesome job, @glenebob https://github.com/glenebob !

—
Reply to this email directly or view it on GitHub
#388 (comment).

@franciscojunior

Copy link
Copy Markdown
Member

Thanks Francisco :)

You are welcome, Glen! You rock!

Yes, the length is optimization. That way the stream never has to call GetByteCount() to determine if/how much to allocate ahead.

Great!
Thanks for the feedback and clarification.

@roji

roji commented Oct 20, 2014

Copy link
Copy Markdown
Member

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).

Comment thread Npgsql/NpgsqlBufferedStream.cs Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a public field?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@roji

roji commented Oct 24, 2014

Copy link
Copy Markdown
Member

@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.

@roji

roji commented Oct 24, 2014

Copy link
Copy Markdown
Member

Some more:

  • I see you added a flag performNetworkByteOrderSwap. Is there any case where NpgsqlBufferedStream should not perform network to host? If not it can be removed...
  • We should add a connstring param to allow the user to set the buffer size rather than fixing it at 8192 (I'll take care of this later).
  • Just a thought: why not use the same buffer for both reads and writes, like .NET BufferedStream does? I don't think there's a case in Npgsql where we need to read and write "simultaneously", this would save some memory and simplify the class state?

I have a few other tweaks I'd do but nothing very important, I'll wait around until you finish your good work @glenebob.

@glenebob

Copy link
Copy Markdown
Contributor Author

On Fri, Oct 24, 2014 at 1:11 AM, Shay Rojansky [email protected]
wrote:

@glenebob https://github.com/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.

That's one of my plans for the weekend, to do some optimizations for ASCII
strings, and also to add support for writing length prefix if needed. It
may be that passing in length then becomes entirely useless, in which case
I will remove it.

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 #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 #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...

MemoryStream is used in ReadString() and WriteString(), and in the query
re-writer - so far. We've barely scratched the surface in terms of where it
could be used. I've only used it so far in the most obvious (to me) places

  • remember, we're still in the proof of concept phase. I also still think
    that a buffer pool may be a useful optimization for Npgsql, in which case
    our own MemoryStream will be essential.

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.

Are you trying to out-micro-optimize me? I think if we get to the point
that virtual function overhead is a real concern, we should all just get
together and have a drink and celebrate a really efficient implementation :)

-Glen

—
Reply to this email directly or view it on GitHub
#388 (comment).

@roji

roji commented Oct 24, 2014

Copy link
Copy Markdown
Member

MemoryStream is used in ReadString() and WriteString(), and in the query
re-writer - so far. We've barely scratched the surface in terms of where it
could be used. I've only used it so far in the most obvious (to me) places

  • remember, we're still in the proof of concept phase. I also still think
    that a buffer pool may be a useful optimization for Npgsql, in which case
    our own MemoryStream will be essential.

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.

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.

Are you trying to out-micro-optimize me? I think if we get to the point that virtual function overhead is a real concern, we should all just get together and have a drink and celebrate a really efficient implementation :)

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.
@glenebob

Copy link
Copy Markdown
Contributor Author

I just pushed up another commit to the stream PR.

On Fri, Oct 24, 2014 at 11:04 AM, Shay Rojansky [email protected]
wrote:

MemoryStream is used in ReadString() and WriteString(), and in the query
re-writer - so far. We've barely scratched the surface in terms of where it
could be used. I've only used it so far in the most obvious (to me) places

  • remember, we're still in the proof of concept phase. I also still
    think that a buffer pool may be a useful optimization for Npgsql, in which
    case our own MemoryStream will be essential.

    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.

For simple queries, we definitely have to construct the query buffer ahead
of time so that we can write a length prefix before sending it out on the
wire. I don't think we'll be getting away from NpgsqlMemoryStream entirely.

This costs us a fair amount of GC overhead, because each simply query
requires a fresh MemoryStream, and some number of byte[]'s as the buffer
grows, not to mention the copy overhead on buffer re-alloc. Not to harp,
but a buffer pool would go a long way here, partly because we could
eliminate the GC overhead, and partly because we could over-allocate much
more aggressively to avoid copy operations without putting even more strain
in the GC.

-Glen

@FransBouma

Copy link
Copy Markdown
Contributor

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.

FB

MemoryStream is used in ReadString() and WriteString(), and in the
query re-writer - so far. We've barely scratched the surface in terms
of where it could be used. I've only used it so far in the most
obvious (to me) places

  • remember, we're still in the proof of concept phase. I also still
    think that a buffer pool may be a useful optimization for Npgsql, in
    which case our own MemoryStream will be essential.

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.

For simple queries, we definitely have to construct the query buffer ahead of time so that we can
write a length prefix before sending it out on the wire. I don't think we'll be getting away from
NpgsqlMemoryStream entirely.

This costs us a fair amount of GC overhead, because each simply query requires a fresh MemoryStream,
and some number of byte[]'s as the buffer grows, not to mention the copy overhead on buffer re-alloc.
Not to harp, but a buffer pool would go a long way here, partly because we could eliminate the GC
overhead, and partly because we could over-allocate much more aggressively to avoid copy operations
without putting even more strain in the GC.

-Glen

—
Reply to this email directly or view it on GitHub
#388 (comment) .
https://github.com/notifications/beacon/ADdd8kIlc5Bhk0AE5lUNQ_XTqDejHVc3ks5nHIVMgaJpZM4CwXKI.gif

@Emill

Emill commented Oct 26, 2014

Copy link
Copy Markdown
Contributor

Den 26 okt 2014 06:59 skrev "Glen Parker" [email protected]:

I just pushed up another commit to the stream PR.

On Fri, Oct 24, 2014 at 11:04 AM, Shay Rojansky [email protected]
wrote:

MemoryStream is used in ReadString() and WriteString(), and in the query
re-writer - so far. We've barely scratched the surface in terms of where it
could be used. I've only used it so far in the most obvious (to me) places

  • remember, we're still in the proof of concept phase. I also still

think that a buffer pool may be a useful optimization for Npgsql, in which
case our own MemoryStream will be essential.

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.

For simple queries, we definitely have to construct the query buffer ahead
of time so that we can write a length prefix before sending it out on the
wire. I don't think we'll be getting away from NpgsqlMemoryStream entirely.

This costs us a fair amount of GC overhead, because each simply query
requires a fresh MemoryStream, and some number of byte[]'s as the buffer
grows, not to mention the copy overhead on buffer re-alloc. Not to harp,
but a buffer pool would go a long way here, partly because we could
eliminate the GC overhead, and partly because we could over-allocate much
more aggressively to avoid copy operations without putting even more strain
in the GC.

Why? If we know the length of the query (GetByteCount), we can calculate
the message length in advance.

-Glen

—
Reply to this email directly or view it on GitHub.

@roji

roji commented Oct 26, 2014

Copy link
Copy Markdown
Member

For simple queries, we definitely have to construct the query buffer ahead of time so that we can write a length prefix before sending it out on the wire. I don't think we'll be getting away from NpgsqlMemoryStream entirely.

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:

  • Call GetByteCount() (extra pass) to figure out the precise length, write it out, then use Encoder.Convert() to chunk-encode the string into our buffer: fill out the buffer, write to underlying, fill again, write again...
  • Allocate a new buffer large enough to contain GetMaxByteCount(), encode into it and write that. This saves the extra pass done by GetByteCount() above at the cost of allocating memory (so classic CPU/memory tradeoff). However, instead of allocating this one-use buffer can be pooled.

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 :)

@roji

roji commented Oct 26, 2014

Copy link
Copy Markdown
Member

@FransBouma, regarding your comment:

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.

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.

@FransBouma

Copy link
Copy Markdown
Contributor

@FransBouma https://github.com/FransBouma , regarding your comment:

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.

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).

TDS is the protocol (like extended query protocol) of SQL server. 

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.

That would work, as a datareader consumer never accesses that row anyway, even GetValues() copies data over to a supplied array. One caveat: rows might not have the same size in bytes so this might not work out, e.g. with byte arrays in the result or varying chars, but I don't know whether these are sent separately by the server or not. 

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.

@Emill

Emill commented Oct 26, 2014

Copy link
Copy Markdown
Contributor

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:

  • Call GetByteCount() (extra pass) to figure out the precise length, write it out, then use Encoder.Convert() to chunk-encode the string into our buffer: fill out the buffer, write to underlying, fill again, write again...
  • Allocate a new buffer large enough to contain GetMaxByteCount(), encode into it and write that. This saves the extra pass done by GetByteCount() above at the cost of allocating memory (so classic CPU/memory tradeoff). However, instead of allocating this one-use buffer can be pooled.

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.

  • If there is definitely space in the buffer, write the string first and then the length (i.e. in reverse order).
  • Else, first run GetByteCount() to get the number of bytes to be written, write this number to the buffer. Then comes the cool stuff: always encode (byte capacity left in buffer)/3 chars and write them to the buffer while there is enough space to do this. When the buffer is full, write it to the underlying stream. If we approach the end of the string and there is enough space, just write it.

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.

@roji

roji commented Oct 26, 2014

Copy link
Copy Markdown
Member

@FransBouma:

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.

That would work, as a datareader consumer never accesses that row anyway, even GetValues() copies data over to a supplied array. One caveat: rows might not have the same size in bytes so this might not work out, e.g. with byte arrays in the result or varying chars, but I don't know whether these are sent separately by the server or not.

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.

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.

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.

@roji

roji commented Oct 26, 2014

Copy link
Copy Markdown
Member

@Emill, your implementation is almost exactly what I had in mind, it looks like awesome work :)

@glenebob, let us know what you think about it and how you're doing in general.

@Emill

Emill commented Oct 26, 2014

Copy link
Copy Markdown
Contributor

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
They have a "union" with struct types and a variable _type that indicates what type it is. If the requested type doesn't correspond with the stored value, boxing/unboxing is done: http://referencesource.microsoft.com/#System.Data/data/System/Data/SqlClient/SqlBuffer.cs#259

@roji

roji commented Oct 26, 2014

Copy link
Copy Markdown
Member

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.

@Emill

Emill commented Oct 26, 2014

Copy link
Copy Markdown
Contributor

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#.

@roji

roji commented Oct 29, 2014

Copy link
Copy Markdown
Member

Although what about types like byte[] and string which are reference types...

@roji

roji commented Oct 30, 2014

Copy link
Copy Markdown
Member

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?

Comment thread Npgsql/NpgsqlBufferedStream.cs Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use + instead of -?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. Good catch. Thank you.

@Emill

Emill commented Oct 31, 2014

Copy link
Copy Markdown
Contributor

How is the PopulateReadBuffer supposed to work?
Should it read at least as many bytes that is requested?
Now it reads everything between 0 bytes up to the end of the buffer, but returns true only when it actually read as many bytes as requested.

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.

Comment thread Npgsql/NpgsqlBufferedStream.cs Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@roji

roji commented Oct 31, 2014

Copy link
Copy Markdown
Member

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...

@roji

roji commented Oct 31, 2014

Copy link
Copy Markdown
Member

@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.

@roji

roji commented Oct 31, 2014

Copy link
Copy Markdown
Member

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).

Comment thread Npgsql/QueryManager.cs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't it better to simply do BackendEncoding.UTF8Encoding.GetByteCount/.GetBytes together with the header and null-terminator?

@glenebob

glenebob commented Nov 2, 2014

Copy link
Copy Markdown
Contributor Author

On Fri, Oct 31, 2014 at 12:53 AM, Shay Rojansky [email protected]
wrote:

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).

The stream contract says that Read() can return fewer bytes than asked for;
BufferedStream just honors the contract. If we want to deviate from the
contract, then we would really need to abandon the Stream class altogether,
which IMO would be a bad idea. I think it's far better to honor the
contract. The standard stream interface is extremely well established and
understood.

I added void ReadExact() to achieve this functionality. It could just as
efficiently be an extension, but IMO there's no good reason not to roll all
of our stream class needs into these new ones.

-Glen

@glenebob

glenebob commented Nov 2, 2014

Copy link
Copy Markdown
Contributor Author

On Fri, Oct 31, 2014 at 12:43 AM, Shay Rojansky [email protected]
wrote:

@glenebob https://github.com/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.

—
Reply to this email directly or view it on GitHub
#388 (comment).

I'll do it. I got used to writing the way I did here at work, and forgot
Npgsql was more standardized on leading underscores. It's no problem.

-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.
@roji
roji force-pushed the master branch 2 times, most recently from e1d8c57 to 1f140e5 Compare January 14, 2015 02:37
@roji
roji force-pushed the master branch 2 times, most recently from 1236d1f to e8ae2e0 Compare April 12, 2015 07:50
@roji
roji force-pushed the master branch 5 times, most recently from 2fc8944 to 3eb6fa4 Compare April 29, 2015 14:47
@roji

roji commented Aug 9, 2015

Copy link
Copy Markdown
Member

Closing this as NpgsqlBuffer has now been implemented differently in Npgsql 3.0. Thanks for the invaluable discussion and attempts around this...!

@roji roji closed this Aug 9, 2015
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.

5 participants