Skip to content

Commit dc744ce

Browse files
committed
avoids alloc in unserialize()
1 parent 85b5f69 commit dc744ce

File tree

1 file changed

+27
-17
lines changed

1 file changed

+27
-17
lines changed

src/Peachpie.Library/Serialization.cs

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using System.IO;
1111
using System.Diagnostics;
1212
using System.Reflection;
13+
using System.Buffers;
1314

1415
namespace Pchp.Library
1516
{
@@ -814,27 +815,36 @@ PhpValue ReadString()
814815

815816
if (length != 0)
816817
{
817-
var bytes = new byte[length];
818-
819-
// :"<bytes>";
820-
Consume(Tokens.Colon);
821-
Consume(Tokens.Quote);
822-
if (_stream.Read(bytes, 0, length) != length)
823-
{
824-
ThrowEndOfStream();
825-
}
826-
Consume(Tokens.Quote);
827-
828-
//
818+
var bytesBuffer = ArrayPool<byte>.Shared.Rent(length);
819+
829820
try
830821
{
831-
// unicode string
832-
return PhpValue.Create(_encoding.GetString(bytes));
822+
var bytes = bytesBuffer.AsSpan(0, length);
823+
824+
// :"<bytes>";
825+
Consume(Tokens.Colon);
826+
Consume(Tokens.Quote);
827+
if (_stream.Read(bytes) != length)
828+
{
829+
ThrowEndOfStream();
830+
}
831+
Consume(Tokens.Quote);
832+
833+
//
834+
try
835+
{
836+
// unicode string
837+
return PhpValue.Create(_encoding.GetString(bytes));
838+
}
839+
catch (DecoderFallbackException)
840+
{
841+
// binary string
842+
return PhpValue.Create(new PhpString(bytes.ToArray()));
843+
}
833844
}
834-
catch (DecoderFallbackException)
845+
finally
835846
{
836-
// binary string
837-
return PhpValue.Create(new PhpString(bytes));
847+
ArrayPool<byte>.Shared.Return(bytesBuffer);
838848
}
839849
}
840850
else

0 commit comments

Comments
 (0)