• Avalanche.Core
Search Results for

    Show / Hide Table of Contents
    • Avalanche.Accessor
      • Introduction
      • IAccessor
        • IAccessor
        • IFieldAccessor
        • IListAccessor
        • IMapAccessor
        • IRecordAccessor
        • IOneOfAccessor
        • IAnyAccessor
      • Dto
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Articles
        • Dependency Injection
        • AccessorMessages
    • Avalanche.Binding
      • Introduction
    • Avalanche.Configuration
      • Introduction
      • Configuration Binding
      • ConfigurationExtensions
      • MemoryConfiguration
      • PrintTree
      • Saving IOptions
      • Yaml
    • Avalanche.Converter
      • Introduction
      • EnumConverter
      • Func<,>
      • HexConverter
      • PrimitiveConverter
      • StringConverter
    • Avalanche.Core
      • License
    • Avalanche.DataType
      • Introduction
      • DataType
        • IDataType
        • IListType
        • IMapType
        • IRecordType
        • IFieldType
        • IOneOfType
        • IAnyType
        • IStringType
        • IValueType
        • IIntegerType
        • IEnumerationType
        • IFloatingPointType
      • Dto
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • Enum
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
        • DtoTarget(IDataType)
        • IntermediateTarget
      • Articles
        • DataTypeRequest
        • PrintTree
        • DataTypeMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
        • CustomAttributeUtilities
        • ToStringRequest
    • Avalanche.FileSystem
      • Introduction
      • Abstractions
        • IFileSystemBrowse
        • IFileSystemCreateDirectory
        • IFileSystemDelete
        • IFileSystemFileAttribute
        • IFileSystemMount
        • IFileSystemMove
        • IFileSystemObserve
        • IFileSystemOpenStream
        • IFileSystemOpenMemory
        • IEvent
        • IEntry
        • IOption
        • IToken
      • FileSystem
      • VirtualFileSystem
      • MemoryFileSystem
      • EmbeddedFileSystem
      • HttpFileSystem
      • Decoration
      • IFileProvider
      • Utilities
        • Dispose
        • FileDictionary
        • FileScanner
        • FilterEnumerable
        • OperationSession
        • PollingFilterWatchToken
        • VisitTree
      • Article
        • Examples
        • PrintTree
    • Avalanche.Identity
      • Introduction
      • Identity
      • IdentityParts
      • IdentityInterner
      • IdentityComparer
      • Print Tree
      • IdentityAccessors
        • Introduction
        • TypeName
    • Avalanche.Localization
      • Introduction
      • Localization
      • LocalizationFile
      • LocalizationFiles
      • LocalizationFileSystem
      • LocalizationFileFormat
      • LocalizationLine
      • LocalizationLines
      • TemplateFormat
      • CultureProvider
      • FallbackCultureProvider
      • ResourceManager
      • LocalizationError
      • Microsoft.Extensions
        • Introduction
        • DependencyInjection
        • FileProvider
        • Logging
        • ITextLocalizer
        • IFileLocalizer
        • Localization
      • Asp.Net
        • Introduction
        • Supplying localization
        • Inject to pages
        • Culture Assigned
        • Minimalistic Api
        • Diagnostics
      • Pluralization
        • Introduction
        • Multiple plural parameters
        • Custom PluralRules
        • Invariant Culture
        • Unit Prefix
        • IPluralRule
        • IPluralNumber
        • IPluralRules
        • CLDRs
        • Unicode.CLDR40
        • Unicode.CLDR41
        • Unicode.CLDR42
        • Unicode.CLDR43
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
        • Printing templates
    • Avalanche.Memory
      • Introduction
      • IMemory<T>
      • BlockMemory<T>
      • FileMemory
      • ListMemory<L, T>
      • MemoryMemory<T>
      • MMFMemory<T>
      • PointerMemory<T>
      • Slice<M, T>
      • StreamMemory
      • Concurrency
        • RWLockedMemory
        • SynchronizedMemory
      • Serialization
        • Benchmarks
        • Fixed<T>
        • Variable<T>
        • ZigZag<T>
        • StringEncoding
      • Articles
        • Fixed-size and Variable-sized
        • IBlockPool<T>
        • Print Tree
        • Read and Write events
        • Stream View
        • Zero Heap
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageDescriptionsBase
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Microsoft.Extensions
        • DependencyInjection
      • Articles
        • Aggregate Messages
        • Localization
        • Localization Templates
        • Logging
        • Validation
    • Avalanche.Module
      • Introduction
      • IServiceCollection
      • IServiceBuilder
      • IHostBuilder
      • Dependencies
    • Avalanche.Options
      • Introduction
      • OptionsExtensions
      • OptionsMonitorCast
    • Avalanche.Protobuf
      • Introduction
    • Avalanche.Service
      • Introduction
      • Service
        • Introduction
        • IService
        • IServiceDisposable
        • IServiceDecoration
        • IServiceCast
        • IServiceObservable
        • IServiceContainer
        • Construction
        • Query
        • CancellationToken
        • CachePolicy
        • Scope
      • Handler
        • Introduction
        • IHandler
        • IHandlerCast
        • IHandlerDecoration
        • IHandlerWithOrder
        • CancellationToken
        • Cyclicity
        • Delegates
        • Invokable
        • ExportAttribute
        • OrderAttribute
        • PrintTree
        • Recursion
      • Query
        • Introduction
        • IQuery
        • IQueryCast
        • IQueryDecoration
      • Entry
        • Introduction
        • IEntry
        • IEntryCast
        • IEntryDecoration
        • IEntryObservable
        • IEntryVisitable
        • EntryState
      • Request
        • Introduction
        • IRequest
        • IRequestFor
        • IRequestToBeCached
        • IRequestToBeDisposed
        • RequestAttribute
        • ContextParameterAttribute
        • Print Tree
      • Dependency Injection
        • Introduction
        • Asp.Net
        • ServiceRequest<T>
        • Decorating a service
        • Handler
        • CachePolicy
        • CancellationToken
        • QueryLogger
        • IHostBuilder
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • StorageMessages
        • ItfMessages
        • Win32Messages
        • WindowsMessages
        • SspiMessages
        • CertMessages
        • MediaServerMessages
        • SetupApiMessages
        • ScardMessages
        • ComPlusMessages
        • ClrMessages
        • UserModeFilterManagerMessages
        • GraphicsMessages
        • TpmServicesMessages
        • TpmSoftwareMessages
        • PlaMessages
        • FveMessages
        • FwpMessages
        • NdisMessages
        • DltMessages
      • System
        • Introduction
        • AccessControlMessages
        • AggregateMessages
        • AppDomainMessages
        • ArgumentMessages
        • ArgumentNullMessages
        • ArgumentOutOfRangeMessages
        • ArithmeticMessages
        • ArrayMessages
        • AssemblyMessages
        • BadImageFormatMessages
        • CodeContractMessages
        • CodePageMessages
        • CollectionsMessages
        • CompilerServiceMessages
        • CryptographyMessages
        • CultureMessages
        • DiagnosticsMessages
        • EventSourceMessages
        • ExecutionEngineMessages
        • FormatMessages
        • HostProtectionMessages
        • IOMessages
        • IndexOutOfRangeMessages
        • InteropServiceMessages
        • InvalidCastMessages
        • InvalidOperationMessages
        • IsolatedStorageMessages
        • LazyMessages
        • MarshalerMessages
        • MemoryMessages
        • MiscellaneousMessages
        • NotImplementedMessages
        • NotSupportedMessages
        • ObjectDisposedMessages
        • OperationCanceledMessages
        • OverflowMessages
        • PlatformMessages
        • PolicyMessages
        • PrincipalMessages
        • ProgramMessages
        • ReferenceMessages
        • ReflectionMessages
        • RegionMessages
        • RemotingMessages
        • ResourcesMessages
        • SecurityMessages
        • SerializationMessages
        • StackMessages
        • TaskMessages
        • TextMessages
        • ThreadingMessages
        • TimeZoneMessages
        • TypeMessages
        • XmlMessages
      • HttpStatusCode
      • OpcUaStatusCode
    • Avalanche.Template
      • Introduction
      • TemplateFormats
      • ITemplatePrintable
      • ITemplateFormatPrintable
      • ITemplateText
      • ITemplateBreakdown
      • ITemplateFormat
      • ITemplateFormats
      • Extract Arguments
      • Emplacement
    • Avalanche.Tokenizer
      • Introduction
      • IToken
      • ITokenizer
      • Tokenizers
    • Avalanche.Utilities
      • Introduction
      • Collections
        • ArrayList
        • ArrayUtilities
        • BijectionMap
        • CachedSelect
        • DictionaryAdapter
        • EnumerableExtensions
        • LocakableDictionary
        • LockableList
        • MapList
        • Pipe
        • RingQueue
        • StructList
        • Tuples
        • TupleUtilities
      • Comparers
        • IGraphComparer
        • IGraphComparable
        • AlphaNumericComparer
        • EnumerableComparer
        • EnumerableGraphComparer
        • ReferenceComparer
        • KeyValuePairComparer
        • DefaultComparerProvider
        • RecordComparer
      • Cloners
        • ICloner
        • IGraphCloner
        • IGraphCloneable
        • ListCloner
        • DictionaryCloner
        • FieldCloner
        • PassthroughCloner
        • RecordCloner
        • ClonerProvider
      • Dispose
        • IDisposeAttachable
        • IDisposeBelatable
      • Provider
        • Introduction
        • ProviderBase
        • Delegate
        • Pipe
        • Cache
        • ResultCapture
        • AsReadOnly
        • SharedResource
        • AsService
        • IProviderEvent
      • Record
        • IRecordDescription
        • IFieldDescription
        • IConstructorDescription
        • IConstructionDescription
        • IParameterDescription
        • IRecordProviders
        • RecordDelegates
          • RecordCreate
          • RecordClone
          • RecordCopy
          • IRecordDelegates
        • FieldDelegates
          • FieldRead
          • FieldWrite
          • RecreateWith
          • IFieldDelegates
      • Reflection
        • EnumDescription
      • String
        • IEscaper
        • UnicodeString
        • Hex
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • ITreeNode
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    Zero Heap Use

    ListMemory<L, T>, MemoryMemory<T>, PointerMemory<T> and Slice are structs. They can be used with zero heap allocations by not boxing as IMemory<T>.

    byte[] array = new byte[50];
    // Create fixed-sized memory
    var arrayMemory = new MemoryMemory<byte>(array);
    // Adapt to variable-sized
    var arrayMemoryAllocation = new Slice<MemoryMemory<byte>, byte>(
        decoree: arrayMemory,
        offset: 10L,
        count: 9L,
        allocation: 20L);
    

    ArrayPool

    ListMemory<L, T> can adapt array pool rented recyclable blocks into memory access.

    // Rent array
    byte[] array = ArrayPool<byte>.Shared.Rent(50);
    
    try
    {
        // Create fixed-sized memory
        var arrayMemory = new MemoryMemory<byte>(array);
        // Adapt to variable-sized
        var arrayMemoryAllocation = new Slice<MemoryMemory<byte>, byte>(
            decoree: arrayMemory,
            offset: 10L,
            count: 9L,
            allocation: 20L);
    
        WriteLine(arrayMemory.IsFixedSize);            // 'True'
        WriteLine(arrayMemoryAllocation.IsFixedSize);  // 'False'
        WriteLine(arrayMemoryAllocation.Count);        // '9'
        WriteLine(arrayMemoryAllocation.MaxCount);     // '20'
    
        // Modify content
        arrayMemoryAllocation.Add(item: 10);
        arrayMemoryAllocation.Insert(0L, 9);
        arrayMemoryAllocation.Count = 5L;
    
        // Clear
        arrayMemoryAllocation.Clear();
        WriteLine(arrayMemoryAllocation.Count);        // '0'
    }
    finally
    {
        // Return
        ArrayPool<byte>.Shared.Return(array);
    }
    

    Span<T>

    PointerMemory<T> adapts Span<T> into memory in an unsafe pointer assignment.

    // Element count
    int count = 4096;
    // Allocate from from stack (Note that there is 1.5MB of stack per thread)
    Span<byte> buf = stackalloc byte[count];
    // Adapt to memory access
    var bufMemory = new PointerMemory<byte>(buf);
    // Adapt to variable-sized
    var slice = new Slice<PointerMemory<byte>, byte>(
        decoree: bufMemory,
        offset: 0L,
        count: 0L,
        allocation: count);
    
    // Increment content to 'buf'
    for (int i = 0; i < 4096; i++)
        slice.Add((byte)i);
    

    Block Pool

    BlockMemory rents blocks from array pool. BlockPool itself is a heap object, but the content is held in recyclable blocks when pool is provided as constructor argument.

    // Create array pool allocating
    using IMemory<byte> memory = new BlockMemory<byte>(ArrayBlockPool<byte>.Instance) { LazyAllocate = true, ClearReturnedBlocks = false };
    // Allocate
    memory.Count = 4096L;
    

    Rental Memory

    BlockMemory<T>.CleanPool.Rent() rents a memory from object pool. Dispose() returns it to the pool. The rented memory is not synchronzied for concurrent usage as is.

    // Rent dirty memory (non-synchronized)
    IMemory<byte> memory = BlockMemory<byte>.CleanPool.Rent();
    // Allocate 100GB (lazy)
    memory.Count = 100L * 1024L * 1024L * 1024L;
    // Return to pool
    memory.Dispose();
    

    BlockMemory<T>.DirtyPool.Rent() doesn't zero pages upon rent or return. Previous data mat be revealed. This version is used for non-security critical, highly efficient "zero heap" heap-assignable memory objects.

    // Rent dirty memory (non-synchronized)
    IMemory<byte> memory = BlockMemory<byte>.DirtyPool.Rent();
    // Allocate 100GB (lazy)
    memory.Count = 100L * 1024L * 1024L * 1024L;
    // Return to pool
    memory.Dispose();
    

    Both pools use the same ArrayPool<T>.Shared.

    Full Example

    Full example
    using System.Buffers;
    using Avalanche.Memory;
    using static System.Console;
    
    public class zeroheap
    {
        public static void Run()
        {
            {
                // <01>
                byte[] array = new byte[50];
                // Create fixed-sized memory
                var arrayMemory = new MemoryMemory<byte>(array);
                // Adapt to variable-sized
                var arrayMemoryAllocation = new Slice<MemoryMemory<byte>, byte>(
                    decoree: arrayMemory,
                    offset: 10L,
                    count: 9L,
                    allocation: 20L);
                // </01>
            }
            {
                // <11>
                // Rent array
                byte[] array = ArrayPool<byte>.Shared.Rent(50);
    
                try
                {
                    // Create fixed-sized memory
                    var arrayMemory = new MemoryMemory<byte>(array);
                    // Adapt to variable-sized
                    var arrayMemoryAllocation = new Slice<MemoryMemory<byte>, byte>(
                        decoree: arrayMemory,
                        offset: 10L,
                        count: 9L,
                        allocation: 20L);
    
                    WriteLine(arrayMemory.IsFixedSize);            // 'True'
                    WriteLine(arrayMemoryAllocation.IsFixedSize);  // 'False'
                    WriteLine(arrayMemoryAllocation.Count);        // '9'
                    WriteLine(arrayMemoryAllocation.MaxCount);     // '20'
    
                    // Modify content
                    arrayMemoryAllocation.Add(item: 10);
                    arrayMemoryAllocation.Insert(0L, 9);
                    arrayMemoryAllocation.Count = 5L;
    
                    // Clear
                    arrayMemoryAllocation.Clear();
                    WriteLine(arrayMemoryAllocation.Count);        // '0'
                }
                finally
                {
                    // Return
                    ArrayPool<byte>.Shared.Return(array);
                }
                // </11>
            }
            {
                // <21>
                // Element count
                int count = 4096;
                // Allocate from from stack (Note that there is 1.5MB of stack per thread)
                Span<byte> buf = stackalloc byte[count];
                // Adapt to memory access
                var bufMemory = new PointerMemory<byte>(buf);
                // Adapt to variable-sized
                var slice = new Slice<PointerMemory<byte>, byte>(
                    decoree: bufMemory,
                    offset: 0L,
                    count: 0L,
                    allocation: count);
    
                // Increment content to 'buf'
                for (int i = 0; i < 4096; i++)
                    slice.Add((byte)i);
                // </21>
            }
            {
                // <31>
                // Create array pool allocating
                using IMemory<byte> memory = new BlockMemory<byte>(ArrayBlockPool<byte>.Instance) { LazyAllocate = true, ClearReturnedBlocks = false };
                // Allocate
                memory.Count = 4096L;
                // </31>
            }
    
            {
                // <41>
                // Rent dirty memory (non-synchronized)
                IMemory<byte> memory = BlockMemory<byte>.CleanPool.Rent();
                // Allocate 100GB (lazy)
                memory.Count = 100L * 1024L * 1024L * 1024L;
                // Return to pool
                memory.Dispose();
                // </41>
            }
            {
                // <42>
                // Rent dirty memory (non-synchronized)
                IMemory<byte> memory = BlockMemory<byte>.DirtyPool.Rent();
                // Allocate 100GB (lazy)
                memory.Count = 100L * 1024L * 1024L * 1024L;
                // Return to pool
                memory.Dispose();
                // </42>
            }
        }
    }
    
    In This Article
    Back to top