Does ImmutableList have AsReadOnly like method? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
AsReadOnly() is a convenient method to get a read-only image (not expensive compared to immutable collections' copies) of a collection. I am wondering if ImmutableList has AsReadOnly like method? If no, any easy way to implement similarly?

Immutable collections are inherently read-only. You can easily check in the documentation that ImmutableList<T> already implements IReadOnlyList<T> and IReadOnlyCollection<T> interfaces.
Memory is not allocated when you access elements from immutable collection. On the other hand, when you add an element to some immutable data structure, a new immutable collection is created (and some memory is used). Many immutable collections' implementations do not copy all the data to a new collection but instead share some data from with the old one, so in most cases you should not be too concerned with memory usage/allocation time.
Some collections, e.g. ImmutableHashSet<T>, have a documentation which states that they are optimized in terms of number of memory allocations.
The idea behind sharing some data between immutable collection is not complicated. Wikipedia has an simple example (with a nice diagram) showing how memory can be saved in case of immutable singly-linked lists.

ImmutableList<T> is copied by reference so is perfectly safe to pass around without a performance penalty. Thus there is no need for an AsReadOnly method as it wouldn't make it any easier to copy.

Related

Why are Arrays reference types? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
int[] age=new int[5];
After reading many posts and blogs ,I am still not clear about the fact why arrays are reference types.I know this question is like very old and have been asked plenty times but still couldnt find direct answer.
Known things :Since Arrays are allocated on heap,hence they are reference types .
Need to know:Whats the reason behind making(compiler) arrays as reference types?.
Suppose age[0]=5,age[1]=25 ,what is the difficulty in assigning these on stack or make reference to heap if their type was object.why consider heap as accessing time is slow comparatively?.
Why heap ,why not on stack like for structures?.
Several reasons:
value types are passed by value (as in copied). So if you called a method with a value-type array, you'd be copying all the contents.
Stack memory is limited and primarily designed for quick access to parameters that are in current use (as implied by the term stack). Putting a large object onto the stack would cause lookups of other local state to take much longer, because they wouldn't all be on the same cache line in the CPU cache anymore.
Array contents are modifiable. So you'd have all the issues that you have with mutable structs when you tried to set a value, only to find that the copy, not the "original" was modified.
EDIT:
Yes you can use stackalloc in unsafe code. Doesn't make it a good idea.

Best way to pair a Pre-made Class and primitive type C# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Basically, I'm wanting to efficiently pair multiple bool and bytes ( to store values ) with a pre-made class (RenderTarget2D if you must know).
Obviously, I can wrap this all in a class, however there are situations when I will be having many of these, and would like to save on memory where possible (ie use a struct).
I know it's bad behaviour to use a struct with reference variables, and I'd prefer not to just use separate variables to hold the information ( would rather pair it all together ).
Essentially I am wanting a structure to hold a reference to a class, a bool, and a byte, and create a 2D array of this to make many (thus am looking for a mitigate memory usage)
Am I overlooking an obvious solution?
Understanding the question as:
You want something that holds a bool, a byte and an instance of the class RenderTarget2D.
If that is the case you can use Tuple<bool, byte, RenderTarget2d>.
Creating a custom class or struct is also a viable option. In fact there is a proposal for "C# 7" to include language native tuples (that will not be System.Tuple) and as currently written, they will be structs.
You may also want to consider that having a reference to the RenderTarget2d may prolong its lifespan.
Struct vs Class
The struct takes in memory (when compacted) the size of a bool plus the size of a byte plus the size of a reference (to RenderTarget2d). If you have an array of 600 by 600 (360000) of such structs it takes 360000 the size of the struct in memory.
If you use classes, the array will have 360000 references to the actual location of the data that in total takes at least as much as the array of structs.
So using the structs should take less memory...
But when you take a struct from your data structure, you are actually making a copy. So each time you access your array to get a item and read a property of that item, you are actually making a copy of the item and reading the property from that copy.
If you want to update it, you need to read it (that makes a copy as mentioned above) edit it, and then put it back... and that copies the data to the array.
So, if the memory is the main concern. Use struct. To quote Jon Skeet: "so long as you're aware of the consequences".
Using struct also means less RAM round trips. Not only because it avoids resolving the references, but also because the data is guaranteed to be close together. This allows for better performance because the CPU will load a chunk (or the totality) of the data structure in cache and since the code is not using references outside of that it will be able to keep it in cache instead of going to load another thing.

Are there applications for generic classes other than for collections? (Updated !) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Original Questions: I know the question sounds pretty "thin", since generic classes (interfaces) and collections go hand in hand. Out of curiosity and a desire to 'cover all the bases' ... are there uses for these generics other than as collections?
The response is that there are too many possibilities to make for a good thread, so let me try to clarify the question because I ( and probably others) will definitely benefit.
My revised question is:
What are applications of instantiated generics (not methods!) in addition to collections? So, now I know there are many ... however, classified by use... what are they?
A concise format for answers is:
Use: Short description or example
(ie) Collections: The generic allows for collections of objects and with a where T: constraint gives access to methods on all members of the collection. (link or reference).
I'm really eager to hear responses.
You can create not only generic types but also generic methods. Though the most common use of generics is for creating collections they are also used for many other purposes such as containers or algorithms.
class Point<T>
{
T x;
T y;
};
class Math<T>
{
T Add(T a, T b);
};
You should also have a look at this discussion: What is cool about generics, why use them?.
I've used generics for a "EventHandler" (with a restriction on the generic that the parameter implemented my BaseEvent class) when sending events via WCF to another piece of the system.
As the comments note, the answer is unequivocally yes. You use generics whenever multiple types (and ideally all types) should have the same behavior (and occasionally state). Collections are an easy example of this, but there are many, many other situations where this holds true and generics are a good choice.

Dictionary, List or Array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm writing a service where performance is essential, and I'm not sure what is the fastest thing. I have a few Objects (50-200) which each have an ID in them (ints, e.g. 84397 or 23845). Would it be faster to have a Dictionary, a List of KeyValue Pairs or a List with the indexes set to the IDs with the rest having null values or an array with the same idea?
It depends on which operation you want to execute. Let's assume that you want to find an object with a given ID.
The huge array approach is fastest: Accessing myArray[84397] is a constant-time operation O(1). Of course, this approach requires the most memory.
The dictionary is almost as fast but requires less memory, since it uses a hash table internally.
The list of pairs approach is the slowest, since you might have to traverse the whole list to find your entry, which yields O(n) complexity.
Thus, in your situation, I would choose the dictionary, unless the marginally better performance of the huge array is really relevant in your case.
Dictionary<TKey, TValue> uses a hash table internally so I think it would be the fastest one.
Dictionary versus List Lookup time
Also, for a more detailed explaination of the different collections, check out this question.
You can use Hashtables as well. Dictionary internally using it anyway.
but dictionary has an advantage that it is a GENERIC type which gives you type safety.
here is different thread
Dictionary Vs HashTable
I hope it helps you decide.
Praveen

I want to know more about LinkedList<T> [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm learning c# , and I reached the LinkedList<T> type and I still need to know more, like when should I use it, how do I create one, how do I to use it. I just want information.
If any one knows a good article about this subject, or if you can show me some examples with explanation, such as how to create, how to add and remove, and how to deal with nodes and elements.
Thanks in advance. I really enjoy asking questions around here with all the pros answering and helping.
[EDIT] Changed reference to LinkedList<T> instead of "array linkedlist." I think this was what was meant based on the context.
You can find more information on LinkedList<T> at MSDN, including an example of how to create and use one. Wikipedia has a reasonable article on linked lists, including their history, usage, and some implementation details.
Linked is a collection to store sequences of values of the same type, which is a frequent task, e.g. to represent a queue of cars waiting at a stoplight.
There are many different collection types like linked list, array, map, set etc. Which one to use when depends on their properties, e.g.:
do you need some type of ordering?
is the container associative, storing key-value pairs like a dictionary?
can you store the same element twice?
performance measures - how fast is e.g. inserting, removing, finding an element? This is usually given in Big-O notation, telling you how the time required scales with the number of elements in the collection.
Memory footprint and layout. This also can affect performance, due to good/bad locality.
This collection class implements a doubly linked list. It allows you to quickly determine the immediate sibling for a specified item in the collection. Removing an item from the collection automatically resizes it so that it does not leave any gaps.
For more info on LinkedList class, check out LinkedList at MSDN.
Do you know what a standard Linked List is? It's like one of those (doubly linked) but using .NET Generics to allow you to easily store any Type inside of it.
Honestly, I don't use it, I prefer the more basic List or Dictionary.
For more info on Linked Lists, check out wikipedia. As for generics, there are tons of articles here and at MSDN.
linklist are collections.. they can be use as replacements for arrays.. they can dynamically grow in size and has special helper methods that can help the development or the problem solving be faster.. try to view its methods and properties to understand more.
linklist is a generic collection.. meaning can used to declare type safety declarations..

Categories