Created
June 25, 2018 07:46
-
-
Save lahma/b8b3f1a5e324fdbf11f570fd26589f73 to your computer and use it in GitHub Desktop.
ArrayAccessPerformance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Runtime.CompilerServices; | |
| using BenchmarkDotNet.Attributes; | |
| namespace Jint.Benchmark | |
| { | |
| public class ArrayAccessBenchmark | |
| { | |
| private class PropertyDescriptor | |
| { | |
| } | |
| private PropertyDescriptor[] _dense; | |
| [GlobalSetup] | |
| public void Setup() | |
| { | |
| _dense = new PropertyDescriptor[1000]; | |
| } | |
| [Benchmark] | |
| public bool Access() | |
| { | |
| bool ok = false; | |
| for (uint i = 0; i < 1000; ++i) | |
| { | |
| ok |= TryGetValue(i, out _); | |
| } | |
| return ok; | |
| } | |
| public bool TryGetValue(uint index, out JsValue value) | |
| { | |
| value = JsValue.Undefined; | |
| return TryGetDescriptor(index, out var desc); | |
| } | |
| public class JsValue | |
| { | |
| public static readonly JsValue Undefined = new JsValue(); | |
| } | |
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | |
| private bool TryGetDescriptor(uint index, out PropertyDescriptor descriptor) | |
| { | |
| if (_dense != null) | |
| { | |
| if (index >= _dense.Length) | |
| { | |
| descriptor = null; | |
| return false; | |
| } | |
| descriptor = _dense[index]; | |
| return descriptor != null; | |
| } | |
| descriptor = null; | |
| return false; | |
| } | |
| } | |
| } | |
Author
lahma
commented
Jun 25, 2018
| Method | Mean | Error | StdDev |
|---|---|---|---|
| Access | 1.489 us | 0.0067 us | 0.0056 us |
| Method | Mean | Error | StdDev | Allocated |
|---|---|---|---|---|
| Access | 1.931 us | 0.0072 us | 0.0052 us | 0 B |
Author
The problem goes away by changing the array index validation to check that is less than length instead of not more or equal to lenght:
private bool TryGetDescriptor(uint index, out PropertyDescriptor descriptor)
{
descriptor = null;
if (_dense != null)
{
if (index < _dense.Length)
{
descriptor = _dense[index];
}
return descriptor != null;
}
return false;
}
@lahma thanks for the update!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment