Skip to content

Instantly share code, notes, and snippets.

@lahma
Created June 25, 2018 07:46
Show Gist options
  • Select an option

  • Save lahma/b8b3f1a5e324fdbf11f570fd26589f73 to your computer and use it in GitHub Desktop.

Select an option

Save lahma/b8b3f1a5e324fdbf11f570fd26589f73 to your computer and use it in GitHub Desktop.
ArrayAccessPerformance
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;
}
}
}
@lahma
Copy link
Copy Markdown
Author

lahma commented Jun 25, 2018

BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17134
Intel Core i7-6820HQ CPU 2.70GHz (Skylake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=2.1.300
  [Host]     : .NET Core 2.0.7 (CoreCLR 4.6.26328.01, CoreFX 4.6.26403.03), 64bit RyuJIT
  DefaultJob : .NET Core 2.0.7 (CoreCLR 4.6.26328.01, CoreFX 4.6.26403.03), 64bit RyuJIT

Method Mean Error StdDev
Access 1.489 us 0.0067 us 0.0056 us
BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17134
Intel Core i7-6820HQ CPU 2.70GHz (Skylake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=2.1.300
 [Host]     : .NET Core 2.1.0 (CoreCLR 4.6.26515.07, CoreFX 4.6.26515.06), 64bit RyuJIT
 DefaultJob : .NET Core 2.1.0 (CoreCLR 4.6.26515.07, CoreFX 4.6.26515.06), 64bit RyuJIT

Method Mean Error StdDev Allocated
Access 1.931 us 0.0072 us 0.0052 us 0 B

@lahma
Copy link
Copy Markdown
Author

lahma commented Jun 26, 2018

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;
    }

@adamsitnik
Copy link
Copy Markdown

@lahma thanks for the update!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment