ENHANCED: Faster format/3 for binary streams.

This speeds up web servers considerably when sending binary files.
This commit is contained in:
Markus Triska
2020-05-22 17:30:29 +02:00
parent cbbed310c5
commit 48c0b0ab3c
3 changed files with 52 additions and 2 deletions

View File

@@ -367,8 +367,20 @@ format(Fs, Args) :-
format(Stream, Fs, Args) :-
phrase(format_(Fs, Args), Cs),
( stream_property(Stream, type(binary)) ->
maplist(char_code, Cs, Bytes),
maplist(put_byte(Stream), Bytes)
% maplist(char_code, Cs, Bytes) is currently a lot slower
% than first converting Cs to an atom, and then to codes.
% In the future, we can ideally avoid creating an atom here,
% since an atom leaves traces in the system.
atom_chars(A, Cs),
atom_codes(A, Bytes),
( member(NonByte, Bytes), NonByte > 255 ->
char_code(Char, NonByte),
throw(error(representation_error(Char), format/3))
; true
),
% For binary streams, we use a specialised internal predicate
% that uses only a single "write" operation for efficiency.
'$put_bytes'(Stream, Bytes)
; maplist(put_char(Stream), Cs)
).