I just read this question: are there dictionaries in javascript like python?
One of the answers said that you can use JavaScript objects like Python dictionaries. Is that true? What is the performance of a key lookup in an object? Is it O(1)? Is adding a key to the object also constant time (hashing)?
The V8 design docs imply lookups will be at least this fast, if not faster:
Most JavaScript engines use a dictionary-like data structure as
storage for object properties - each property access requires a
dynamic lookup to resolve the property's location in memory. This
approach makes accessing properties in JavaScript typically much
slower than accessing instance variables in programming languages like
Java and Smalltalk. In these languages, instance variables are located
at fixed offsets determined by the compiler due to the fixed object
layout defined by the object's class. Access is simply a matter of a
memory load or store, often requiring only a single instruction.
To reduce the time required to access JavaScript properties, V8 does
not use dynamic lookup to access properties. Instead, V8 dynamically
creates hidden classes behind the scenes. [...] In V8, an object changes
its hidden class when a new property is added.
It sounds like adding a new key might be slightly slower, though, due to the hidden class creation.
Yes, you can assume that adding a key, and later using it for access are effectively constant time operations.
Under the hood the JS engine may apply some techniques to optimize subsequent lookups, but for the purposes of any algorithm, you can assume O(1).
Take a look at a similar question How does JavaScript VM implements Object property access? and the answer. Here I described the optimization technique used by JS engines and how it affects the key lookup performance. I hope these details help you write more efficient JS code.
Related
I have very simple question.Is there any performance relation about accessing object's properties like object[property] and the number of properties ?? Is there some internal loop or something , same question about hasOwnProperty - any loops or just direct access like array[index] ??
JavaScript is a dynamic programming language: properties can be added to, and deleted from, objects on the fly. This means an object's properties are likely to change. Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk. In these languages, instance variables are located at fixed offsets determined by the compiler due to the fixed object layout defined by the object's class. Access is simply a matter of a memory load or store, often requiring only a single instruction.
use V8 (JavaScript engine) for better performance.
Additional Note:
I did check this previous answer and desire an answer that is more current and that is less Chrome specific: Performance of key lookup in JavaScript object
Assuming a standard javascript “dictionary” object with properties like this:
var myObject = {
Key1: ”Value1”,
Key2: ”Value2”,
Key3: ”Value3”,
…
Key500: ”Value500”
}
Does anyone know if browsers(etc) internally optimize their retrieval of these properties?
A good case might be auto-sort + binary search.
A not-so-good case might be simple linear search.
EcmaScript standards say the browsers can do the internals as they wish:
[browsers,etc] may support [object’s] internal properties with any
implementation-dependent behaviour as long as it is consistent with
the specific host object restrictions stated in this document.
and
The mechanics and order of enumerating the properties … is not
specified.
I'm not really needing to know a specific optimization, I just want to know if they are trying to optimize beyond a simple linear search.
So, does anyone have "inside" knowledge?
It depends on the browser and the JavaScript engine. Google's V8 dynamically creates hidden classes instead of dynamic lookup, to reduce the time used to access properties. Using hidden classes also has the added benefit of using class-based optimizations such as inline caching.
There is more information here under the "Fast Property Access" section. The idea basically comes from this paper: An Efficient Implementation of Self, a Dynamically-Typed Object-Oriented Language Based on Prototypes.
Internet Explorer has a "fast type system" to optimize property access. More details in this presentation.
Mozilla's SpiderMonkey engine uses a property cache (warning: the details are somewhat obsolete, but it basically still uses a property cache).
The new IonMonkey engine uses inline property-caches, but details seem to be scant so far.
Yes. The specification does not require such optimications, as you have already noted, but it can be observed empirically. I tested how quickly keys are grabbed from objects that contain up to 500,000 elements. (test here, be warned that it will freeze your browser for a little while).
The key retrieval time does not increase with the size of the object, which means that it has O(1) time complexity for search.
When adding properties to a JavaScript object are they added in an ordered way (alphabetical etc). And if so does that mean when you lookup a property on a JavaScript object that a quick algorithm is used like a binary tree search? I did a search for this and just found lots of explanations for prototype inheritance which I already understand I'm just interested in how a property is looked up within a single level of the prototype chain.
That entirely depends on the implementation. Google's V8 engine probably does it differently than Firefox's JagerMonkey. And they almost certainly does it different than IE6. Looking up a property in an object is just an interface (a fairly common Map interface as programmers would call it). The only thing Javascript guarantees you is the methods of the interface, no details about implementation, and that's a good thing. It could be a hash table (probably) or it could be a linked list (less likely, but possible) or it could even be a binary search tree.
The point is that we don't know how it's implemented, nor should we. And you should make no assumptions about the implementation. As is common with abstraction in programming, just assume it's magic. :)
Here is a high level description of how v8 does it using hidden classes it then looks up the property value by using the fixed offset provided by the definition of the hidden class. It also confirms that most other implementations use a dictionary type data object.
I am excellent in Javascript, but currently started learning ActionScript. Can anyone teach me the difference between JavaScript Object and ActionScript Object ?
I request answer in few lines of description. Explanation with examples would be appreciated.
ActionScript has two different models in fact.
You can create classical ECMA-script objects either using literals or using the new-operator in conjunction with Function objects. Such objects work according to ECMA-standard.
You can create objects by instantiating ActionScript classes much like you would in Java for example. These objects ensure runtime type safety, i.e. if you try to assign a Foo value to a field typed as Bar you will get a runtime exception (or even a compile time exception if the object's type is known at compile time).
It should be noted, that you can compile AS3 with ECMA-script compatibility mode. In that case, AFAIK all objects will act as ECMA-script objects, sacrificing both execution speed and runtime type safety, but giving you flexibility.
Basically, Actionscript is a conventional Object Oriented Language in which it has Classes defining the structure of the objects instantiated.
JavaScript is a completely different flavour; you don't have access to Classes; you can emulate them (and that's a common trend for someone who's coming from a more conventional OOP mindset), but its strength comes exactly from the freedom you have. In a nutshell:
Objects are Functions - Functions are Objects
Objects are created in runtime, and can serve as a base (prototype), for creating other objects which, in its own advantage, can be morphed and override with new properties and methods, without having a strong bound to the strict definition of a class.
I realize that adding methods to native JavaScript objects (Object, Function, Array, String, etc) is considered bad practice by some, but is there also a performance hit associated with this?
Would instances of native objects take longer to create and/or use up more memory if their prototype has been extended with additional methods?
Would instances of native objects take longer to create and/or use up more memory if their prototype has been extended with additional methods?
No. Neither of those things should happen: each object must maintain a reference to its prototype, but that reference won't get any larger or take any longer to retrieve if more properties are added to the object it references.
Now, if you were to add enough additional methods to the prototype, it might start to impact the time needed to look up methods on the objects of that type. This will vary by implementation, but i would be shocked if you ever noticed a difference (i suspect you'd drive yourself mad trying to remember the names of all those additional methods long before it had a noticeable impact on runtime speed).
Edit: here's a quick & ugly test - it creates 500K instances of Array before and after adding 500K custom methods to the Array.prototype object. No appreciable difference; no worries...