Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions Jint.Benchmark/StringSliceBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using BenchmarkDotNet.Attributes;
using Jint.Native;

namespace Jint.Benchmark;

/// <summary>
/// Isolates String.prototype.slice/substring/substr cost over a large (128K char) string —
/// the dromaeo-object-string shape where large slice results are assigned and discarded
/// (measured: slice = 89.9%, substring = 9.2% of its 1.26 GB/op allocations).
/// SliceSmall guards the small-result path; SliceThenRead guards lazy-materialization cost
/// when the result is actually consumed.
/// </summary>
[MemoryDiagnoser]
[HideColumns("Error", "Gen0", "Gen1", "Gen2")]
public class StringSliceBenchmarks
{
private Engine _engine = null!;
private Prepared<Script> _sliceLargeDiscard;
private Prepared<Script> _substringLargeDiscard;
private Prepared<Script> _sliceSmall;
private Prepared<Script> _sliceThenRead;

[GlobalSetup]
public void Setup()
{
_sliceLargeDiscard = Engine.PrepareScript("""
(function() {
var ret = null;
for (var i = 0; i < 5000; i++) {
ret = str.slice(0);
ret = str.slice(12000, -1);
}
return ret.length;
})();
""", strict: true);

_substringLargeDiscard = Engine.PrepareScript("""
(function() {
var ret = null;
for (var i = 0; i < 5000; i++) {
ret = str.substring(0);
ret = str.substring(12000, str.length - 1);
}
return ret.length;
})();
""", strict: true);

_sliceSmall = Engine.PrepareScript("""
(function() {
var ret = null;
for (var i = 0; i < 5000; i++) {
ret = str.slice(15000, 15005);
ret = str.slice(-1);
ret = str.substr(12000, 5);
}
return ret.length;
})();
""", strict: true);

_sliceThenRead = Engine.PrepareScript("""
(function() {
var n = 0;
for (var i = 0; i < 5000; i++) {
var t = str.slice(12000, -1);
n += t.length;
n += t.charCodeAt(100);
}
return n;
})();
""", strict: true);

_engine = new Engine(static options => options.Strict());
// Build the shared ~128K char base string once (dromaeo-style doubling).
_engine.Execute("""
var str = "aB3$xQ9pLm0_kEwZ";
while (str.length < 131072) {
str += str;
}
""");
_engine.Evaluate(_sliceLargeDiscard);
_engine.Evaluate(_substringLargeDiscard);
_engine.Evaluate(_sliceSmall);
_engine.Evaluate(_sliceThenRead);
}

[Benchmark]
public JsValue SliceLargeDiscard() => _engine.Evaluate(_sliceLargeDiscard);

[Benchmark]
public JsValue SubstringLargeDiscard() => _engine.Evaluate(_substringLargeDiscard);

[Benchmark]
public JsValue SliceSmall() => _engine.Evaluate(_sliceSmall);

[Benchmark]
public JsValue SliceThenRead() => _engine.Evaluate(_sliceThenRead);
}
96 changes: 96 additions & 0 deletions Jint/Native/JsString.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,28 @@ internal static JsString Create(char value)
return new JsString(value);
}

/// <summary>
/// Creates a string for a substring of <paramref name="source"/>. Large slices that cover
/// most of the source are returned as zero-copy views (<see cref="SlicedString"/>); small
/// slices are copied so a short-lived view can never pin a much larger backing string.
/// </summary>
internal static JsString CreateSliced(string source, int start, int length)
{
if (start == 0 && length == source.Length)
{
return new JsString(source);
}

// The view pins the whole source string; only worth it (and safe retention-wise)
// when the slice is large and covers at least half of the source.
if (length >= 512 && length * 2 >= source.Length)
{
return new SlicedString(source, start, length);
}

return new JsString(source.Substring(start, length));
}

internal static JsString Create(int value)
{
var temp = _intToStringJsValue;
Expand Down Expand Up @@ -468,4 +490,78 @@ internal override JsValue DoClone()
return new JsString(ToString());
}
}

/// <summary>
/// Zero-copy view over a section of a backing string, produced by slice/substring/substr
/// for large results. Immutable (unlike <see cref="ConcatenatedString"/>), so it never
/// requires cloning; the flat value is materialized lazily on first <see cref="ToString"/>.
/// </summary>
internal sealed class SlicedString : JsString
{
private readonly string _source;
private readonly int _start;
private readonly int _length;

internal SlicedString(string source, int start, int length)
: base(null!, InternalTypes.String)
{
_source = source;
_start = start;
_length = length;
}

public override string ToString()
{
return _value ??= _source.Substring(_start, _length);
}

public override char this[int index] => _source[_start + index];

public override int Length => _length;

private ReadOnlySpan<char> AsSpan() => _value is not null ? _value.AsSpan() : _source.AsSpan(_start, _length);

internal override JsString EnsureCapacity(int capacity)
{
// base implementation reads _value directly, which may not be materialized yet
return new ConcatenatedString(ToString(), capacity);
}

public override bool Equals(string? other)
{
return other is not null && _length == other.Length && AsSpan().SequenceEqual(other.AsSpan());
}

public override bool Equals(JsString? other)
{
if (other is null)
{
return false;
}

if (ReferenceEquals(this, other))
{
return true;
}

if (other.Length != _length)
{
return false;
}

var otherSpan = other is SlicedString otherSlice ? otherSlice.AsSpan() : other.ToString().AsSpan();
return AsSpan().SequenceEqual(otherSpan);
}

public override int GetHashCode()
{
#if NETFRAMEWORK || NETSTANDARD2_0 || NETSTANDARD2_1
// netstandard2.1 lacks the (ReadOnlySpan<char>, StringComparison) overload
return StringComparer.Ordinal.GetHashCode(ToString());
#else
// same hash as the equivalent flat string instance
return string.GetHashCode(AsSpan(), StringComparison.Ordinal);
#endif
}
}
}
12 changes: 9 additions & 3 deletions Jint/Native/String/StringPrototype.cs
Original file line number Diff line number Diff line change
Expand Up @@ -953,7 +953,7 @@ private static JsValue Substring(JsValue thisObject, JsCallArguments arguments)
return JsString.Create(s[from]);
}

return new JsString(s.Substring(from, length));
return JsString.CreateSliced(s, from, length);
}

/// <summary>
Expand Down Expand Up @@ -982,7 +982,7 @@ private static JsValue Substr(JsValue thisObject, JsCallArguments arguments)
{
return TypeConverter.ToString(s[startIndex]);
}
return s.Substring(startIndex, l);
return JsString.CreateSliced(s, startIndex, l);
}

/// <summary>
Expand Down Expand Up @@ -1230,7 +1230,13 @@ private static JsValue Slice(JsValue thisObject, JsCallArguments arguments)
return JsString.Create(s[from]);
}

return s.Substring(from, span);
if (from == 0 && span == len)
{
// whole-string slice: strings are immutable, the receiver can be returned as-is
return s;
}

return JsString.CreateSliced(s.ToString(), from, span);
}

[JsFunction(Length = 1)]
Expand Down
2 changes: 1 addition & 1 deletion Jint/Runtime/Interop/TypeReference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ public override PropertyDescriptor GetOwnProperty(JsValue property)
}
else
{
var key = jsString._value;
var key = jsString.ToString();

if (_properties?.TryGetValue(key, out var descriptor) != true)
{
Expand Down
Loading