Most efficient way to use an object as a hash key - javascript

I have a situation in which I would greatly benefit from the use of function caching (memoization).
However, my function takes a single argument, whose value is a very large and multi-dimensional Array.
The standard way to do caching ( and the only way that I can think of) is to create a cache property on the function itself (cache is a hash). Each run of the function, you can check for the existence of myFunc.cache[arg] and simply return that value if it exists, otherwise you perform the calculations as normal and add the argument as a property of cache afterwards.
However, it appears that javascript does not try to evaluate the strings used as hash keys when you are creating them and always just treats them as strings. example
I could apply JSON.stringify to the argument, but because the array will large and nested, I am wondering if there is a more efficient way to identify unique arguments.

This question is basically what I was asking without knowing it:
JavaScript Hashmap Equivalent
In my case, the simplest solution is just to manually make the 0th index of my arrays an ID that I can use as the hash key.
Without a means of doing this, or something similar, you have to either create your own hashmap (outlined in the linked question) or wait for the official Map object to be implemented.

Related

What is difference between KnockoutObservable<string[]> and KnockoutObservable<string>[]

What is difference between KnockoutObservable<string[]> and KnockoutObservable<string>[]
When to use either of them?
When you subscribe to KnockoutObservable<string[]>, then you will receive a string array (string[])
The other one is an array of observables (KnockoutObservable<string>), each one resolving to a result with a type string.
When you wish to receive the string array, you should use KnockoutObservable<string[]>
If you want an Observable Array, you should be using https://knockoutjs.com/documentation/observableArrays.html
Unless the typescript facade is doing something unexpected (I'm unfamiliar with it), chances are both an array of Knockout Observables, or a Knockout Observable of type array are going to be incorrect.
But to answer your question, they are going to have very different performance overheads, and different uses.
A plain KnockoutObservable of type array, is only going to update when the entire array is replaced. you will not receive notifications when the array is mutated, I can't think of any reason off the top of my head for using it, except for maybe some really data heavy operations, where you are receiving a stream of array information.
However, an array of KnockOut Observables, will give a really heavy performance overhead.
You are creating a KnockoutObservable for each element . Each of those elements are an individual Knockout Observable that can be listened to independently of each other. Just rather then having a property name to bind to, you have an array and key/index.
In 99% of cases, you are probably looking for an ObservableArray which is different.

When is javascript deoptimizer invoked?

I understand that js' JIT compiler will deoptimize the warm or hot code in case datatype changes in a loop (like one element in array is string whereas rest were int).
But i have few scenarios where i'm not able to understand will the code be deoptimized or not
Same loop is used for two arrays where one array contains strings and other ints. Will compiler deoptimize the code here or create two copies? (I understand it should be two copies).
In case of array of object. Considering all scenarios like
Manipulated sub-property is of different type.
Same sub-properties for each object but one object has one property missing.
Missing property is not manipulated inside the loop.
Missing property is manipulated inside loop (null case is handled).
All objects have different properties (New property is added, or manipulation is done using property location).

send individual parameters versus array of parameters

Is there a general good practice convention regarding sending parameters as individual variables, or to send an array of parameters to a function / method?
Eg.
param1, param2, param3 vs array data
How do you determine which of the two to use, or a combination of both?
My rule of thumb is that as soon as you have more than two parameters, you should switch to passing an aggregate of some sort (Array, Hash, Object, Record, whatever) instead. If it's a case of one or two primary parameters and several options, then put just the options into an aggregate and keep the primaries in their own parameters.
When you ask about an array of arguments, I'm assuming you're talking about arguments that are all of the same type (or similar type). It really depends upon the situation and it's a bit of a compromise between convenience for the caller and convenience for the function implementation. That means a lot of it depends upon what you most want to optimize for. There are no hard and fast rules, but you can use this sort of thinking as guidance:
Use separate arguments if:
The number of arguments is relatively small and usually fixed
The code in the receiving function is much cleaner by having named arguments
The typical way the function call is made is not by building argument lists programatically
Use an array if:
The number of arguments is relatively large or usually variable (caller probably wants to build an array and pass that)
The receiving function is cleaner by processing a variable list of arguments in a loop (this can be done with the arguments object too, but is sometimes simpler with an actual array)
A common way that the function call is made is from a list of arguments that is built programmatically (more convenient for the caller to just be able to pass the array).
The called function wants to be able to easily pass the list of arguments to some other function call. While this can be done without the array by processing the arguments object, it takes more code to do if the args aren't passed in an array to start with.
The caller can generally work-around either issue by using .apply() if the function isn't built to take an array, but the caller has arguments in an array.
FYI (though I don't think this was the main subject of your question), another option is to pass an object with a variable number of properties. The options object is particularly useful when there are a number of different arguments and most or all are optional. The called function can contain default values for all options and the caller can just pass the arguments they want to override the default for. The options object generally isn't the best solution for a variable number of the same type of argument that is better represented in an array or as a list of arguments.

How do I switch between making two variable names be an alias of the same object to making them equal two separate objects?

I have two objects, obj1 and obj2. I want one to have the same properties and values as the other when the user clicks a button, so I write this line:
main.obj1.data=$.extend({},main.someArray[0].data);
But now updating main.obj1.data automatically updates main.someArray[0].data and vice versa. I tested it by checking that this is true with console.logs immediately after that line of code. I thought that this command would clone the objects but not make them aliases of the same object. What am I doing wrong?
I have messy code to sort through before this command...is there anything I might have put in my code before that point which would cause $.extend to no longer work like I think it should?
There is two way to solve this
1.
main.obj1.data={};
$.extend(main.obj1.data,main.someArray[0].data);
2.
main.obj1.data=$.extend(true,{},main.someArray[0].data)
Actually both is doing the same thing
You can read more about $.extend()
jQuery extend copy the values so the copied object shouldn't be linked to the initial object. You can verify that in this jsfiddle: http://jsfiddle.net/cFtA7/ (open your console and run the script).
The first parameter in $.extend(true,{},main.someArray[0].data) serve to deep copy your object. If your object has many levels, use this parameter, otherwise, it's not needed.
I'm guessing, but is that possible that your extend code is on a bind object that is called every time you update either one of the values?

Comparing a string against any other variable to determine type in javascript

I am aware of being able to use typeof, however, i would like to know if using
String(anyVariable) === anyVariable
in order to figure out if anyVariable is a string:
Is a generally valid approach?
Works consistently among browsers?
Has any pitfalls?
I would say do not do that, and use typeof because "String" is used to manipulate a stored piece of text, not compare types. It is best to use the features in their intended use, to assure the most stability, and best practice out of it. Also, the purpose is to extend the type with methods. So you are basically causing more work and processing, instead of just a type comparison. Hopefully that answers it, though this is a question that merely has an "opinion" as an answer. You wouldn't create a new object, assign it to your current object, to check if it is a type of object would you? No, you would just use "typeof".
I can think of no reason to use your method vs. the much simpler typeof. Yours is likely to perform worse (15x slower by Matti's jsperf) and be more complex.
Your method is going to require multiple memory manipulations (creating string object, then assign string value to it) and then need to run the garbage collector afterwards whereas typeof just looks at a property of the internal javascript object.
When in doubt, choose the simplest method that solves your problem.
When in doubt, choose the method that is specified in the language definition for solving your problem.
When in doubt, choose the method that requires less memory manipulation.

Categories