hasOwnProperty and object's properties access - javascript

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.

Related

Class syntax in javascript and OOP paradigm [duplicate]

One of the major advantages with Javascript is said to be that it is a prototype based language.
But what does it mean that Javascript is prototype based, and why is that an advantage?
Prototypal inheritance is a form of object-oriented code reuse. Javascript is one of the only [mainstream] object-oriented languages to use prototypal inheritance. Almost all other object-oriented languages are classical.
In classical inheritance, the programmer writes a class, which defines an object. Multiple objects can be instantiated from the same class, so you have code in one place which describes several objects in your program. Classes can then be organized into a hierarchy, furthering code reuse. More general code is stored in a higher-level class, from which lower level classes inherit. This means that an object is sharing code with other objects of the same class, as well as with its parent classes.
In the prototypal inheritance form, objects inherit directly from other objects. All of the business about classes goes away. If you want an object, you just write an object. But code reuse is still a valuable thing, so objects are allowed to be linked together in a hierarchy. In javascript, every object has a secret link to the object which created it, forming a chain. When an object is asked for a property that it does not have, its parent object will be asked... continually up the chain until the property is found or until the root object is reached.
Each function in JavaScript (which are objects themselves) actually has a member called "prototype", which is responsible for providing values when an object is asked for them. Having this member allows the constructor mechanism (by which objects are constructed from functions) to work. Adding a property to the prototype of a function object will make it available to the constructed object, as well as to all of the objects which inherit from it.
Advantages
There may not be a hard and fast rule as to why prototypal inheritance is an advantageous form of code-reuse. Code reuse itself is advantageous, and prototypal inheritance is a sensible way of going about it. You might argue that prototypal inheritance is a fairly simple model of code reuse, and that code can be heavily reused in direct ways. But classical languages are certainly able to accomplish this as well.
Sidenote: #Andrew Hedges makes a good point, that there are actually many prototypal languages. It's worth noting that these others exist, but also worth noting that none of them are anything close to mainstream. NewtonScript seemed to have some traction for a while, but died with its platform. It's also possible to extend some modern languages in ways which add prototypal capabilities.
A prototype-based language, does not make the distinction of classes vs objects: it simply has objects. A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or at run time. In addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties.
Prototype-based programming is a style of object-oriented programming where classes are not present, and behavior reuse (or inheritance in class-based languages) is performed by cloning existing objects that serve as prototypes.
The advantage/disadvantage is that, we can create new kinds of objects at run time without need for defining classes (static code). Like most features it is upto the developer to turn it to a advantage/disadvantage.
Above is possible because objects are essentially functions in java script (closures too).
Instead of declaring a class structure, you can create objects of the same type, and add to their definition any time you like using the object's prototype.
It's more flexible than the normal way of doing things.
After reading all the answers this is the conclusion
1) Inheritance in which objects are inherited directly from other objects
2) That does not use classes
3) Also called instance based programming or classless prototype oriented programming
4) Behaviour reuse is performed by cloning existing objects that serve as prototypes
5) Object used as template from the new object get initial properties
If you just use objects at runtime instead of a class at compile to build new objects, this opens up the possibility of extending an object without knowing any details about it. Of course, it may become a disadvantage pretty quickly depending on usage. I make no assumptions about the language here, so it is applicable to languages other than javascript which are not as dynamic.
myobject.prototype=unkownobject;
myobject.newproperty=1;
You may get the object from just about anywhere; your own code, from the network, from the database, from external linkage and so on.
Note that, a language don't have to implement prototype inheritance like javascript. In javascript, a prototype object is merely shared, so is its properties, among the inheritors. The alternative is copying over all the properties of the prototype to the new object. Each approach has its strengths in different situations. I like the second more but it isn't what javascript does.
Memory conservation is one of the benefits of prototypal inheritance in JS. In a language like Java, objects generate their own copies of the superclass' instance variables and methods, while in JS, the "super"-object offers get-access to its variables and methods to each "sub"-object that inherits from it without the need to recreate them.

Javascript reference object by an identifier or reference it directly?

I am creating quite many objects in Javascript, which I need to be able to reference to retrieve later, for example through an array. Now I am wondering how to save the object reference in the array.
The objects will interract with an external library, which can function either with object IDs or the object itself. I know Javascript treats object variables like pointers and not object copies, so is it safe to reference the objects directly ?
At first I was thinking "if I save the IDs of the objects, that would keep memory usage low", but is this true ? How much memory does an object variable* consume versus an integer variable ?
*the pointer to the object, not the object data
Also, if saving the objects directly is the way to go, is it ok to use array.push() to add the new object to the array ? Is array.push() creating a copy or does it work like a variable ?
Yes, you can reference the objects directly. If you really care about memory usage, I'd say the way of passing the ids will use more memory since you'll have to maintain another set of mappings.
Passing the objects directly will let the JavaScript engine to work directly with the object references. That's not affecting the memory usage, as long you don't to any cloning.
I believe the relevant question is weather or not saving an integer and using that as an identifier later is more effective than saving a reference to the object.
I'd go with the reference in an array. the size of a reference vs a number is going to be negligible.

What does the standard (HTML5 and EcmaScript 5.1) say about extending host objects in the browser?

What do the recent standards say about extending host objects and their prototypes? E.g. is extending NodeList with a method _forEach or Document with a method _my_query properly defined?
Will I see anything I add to Object.prototype on host objects by the standard?
How do real implementations behave with respect to the relevant standards?
Note: I am not asking whether it is a good idea to extend host objects or their prototypes (although Object.defineProperty makes things a bit easier when it comes to enumerating issues).
ECMAScript 5 does not say anything about host objects' prototype chain.
This is defined in WebIDL.
Specifically, take a look at ECMAScript bindings section, which says:
Unless otherwise specified, the [[Prototype]] internal property of
objects defined in this section is the Object prototype object.
and this, from the following section:
Each ECMAScript global environment ([ECMA-262], section 10.2.3) must
have its own unique set of each of the initial objects, created before
control enters any ECMAScript execution context associated with the
environment, but after the global object for that environment is
created. The [[Prototype]]s of all initial objects in a given global
environment must come from that same global environment.
There's even an example:
iframe.appendChild instanceof Function; // Evaluates to true
Finally, Interface Prototype Object section says (emphasis mine):
The named properties object for a given interface A must have an
internal [[Prototype]] property whose value is as follows:
If A is not declared to inherit from another interface, then the value
of the internal [[Prototype]] property of A is the Array prototype
object ([ECMA-262], section 15.4.4) if the interface was declared with
[ArrayClass], or the Object prototype object otherwise
([ECMA-262], section 15.2.4).
Otherwise, A does inherit from another interface. The value of the
internal [[Prototype]] property of A is the interface prototype object
for the inherited interface.
So now if we look at DOM Level 3, and Document interface we can see that it inherits from Node interface. Node interface does not explicitly inherit from anything else, which means it inherits from Object.prototype.
This is theory :)
In practice, not all browsers follow this behavior, although most of the recent ones certainly do.
The ECMASCRIPT5 spec states :
A web server provides a different host environment for server-side
computation including objects representing requests, clients, and
files; and mechanisms to lock and share data. By using browser-side
and server-side scripting together, it is possible to distribute
computation between the client and server while providing a customised
user interface for a Web-based application.
Each Web browser and server that supports ECMAScript supplies its own host environment,
completing the ECMAScript execution environment.
I do not think it says anything else. This can be read to mean that an implementation can conform to the spec and implement the browser objects however it wants. This has been the case in the past. It does seem logical though to apply the power of the language to the external environment and I believe that all "modern" browsers now do that.
the dom/html elements have an prototype chain as follows:
HTMLElement > Element > Node > Object
hooking in anywhere in the chain where it makes the senes is probly the best bet.

Actionscript Object vs Javascript 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.

Performance of key lookup in JavaScript object

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.

Categories

Resources