in reply to Re^8: How could we "implement" Open Classes in Perl ?
in thread How could we "implement" Open Classes in Perl ?
Identical functions are referenced (in most implementations). This means that identical code gets a reference to the existing version, not a new function.
Hm. Quite hard to verify this, but I've succeeded in disproving it for 3 browser-based implementations and 2 standalone.
If you load the following into a browser, and click the "allocate array" link, and check the memory consumption when the "Hi there" alert is displayed, you'll see the memory consumed by an array of 10000 references to a single function.
<html> <head> <title>Javascript test</title> <script type='text/javascript'> var func = function () { return 12345; }; var size = 100000; var array; function allocateArray() { array = new Array( size ); for( var i = 0; i < size; i++ ) { array[ i ] = func; } alert( 'Hi there' ); } function populateArray() { for( var i=0; i < size; i++ ) { array[ i ] = function () { return 12345; }; } alert( "How's it goin'?" ); } </script> </head> <body> <a href=# onclick=allocateArray()>Allocate array</a> <a href=# onclick=populateArray()>Populate array</a> </body> </html>
If you then click the "populate array" link, and again check the memory when the alert is shown, you'll see the memory consumed when those function references are replaced by references to an "identical" function that's declared in-line.
If the JS interpreter was intelligent enough to recognise that the implementations are identical and somehow 'contant fold' them, there would be no increase in the memory consumption. The reality is, it at least quadruples in every implementation I've tested.
BTW. It's really not a good idea to iterate arrays using for( ... in ..) as you do in Re^6: How could we "implement" Open Classes in Perl ?. See the highlighted box here for details.
|
|---|