473,748 Members | 6,412 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Array creation and memory allocation

Quick question for the gurus out there: in ECMAScript, one can create
a new Array object with a length like so:

var animals = new Array(128);

This creates a new Array object with a "length" property set to 128.
My question: Does this in any sense "preallocat e" memory for any of
these 128 slots? I've seen the word "preallocat e" bandied about, but
my experience with UAs tells me this term is being misused; all 128 of
those "slots" remain "undefined" , as do all non-declared property
names on any object. In writing my own code, I've stayed away from
declaring arrays using the above syntax, as I feel it's somewhat
misleading to indicate that an amount of memory has been allocated
that's in any way proportional to the length given to the
constructor. In fact, I can't really think of much legitimate use for
creating an Array object with 128 "undefined" items, except to confuse
C++ and Java programmers. But, if it's actually allocating memory
here, maybe I'm wrong.

Thanks,
David

Sep 18 '07 #1
5 8010
David Golightly wrote:
Quick question for the gurus out there: in ECMAScript, one can create
a new Array object with a length like so:

var animals = new Array(128);

This creates a new Array object with a "length" property set to 128.
My question: Does this in any sense "preallocat e" memory for any of
these 128 slots? I've seen the word "preallocat e" bandied about, but
my experience with UAs tells me this term is being misused; all 128 of
those "slots" remain "undefined" , as do all non-declared property
names on any object. In writing my own code, I've stayed away from
declaring arrays using the above syntax, as I feel it's somewhat
misleading to indicate that an amount of memory has been allocated
that's in any way proportional to the length given to the
constructor. In fact, I can't really think of much legitimate use for
creating an Array object with 128 "undefined" items, except to confuse
C++ and Java programmers. But, if it's actually allocating memory
here, maybe I'm wrong.
You have it right. I use [] exclusively, for the reasons you presented.
Sep 18 '07 #2
David Golightly wrote:
Quick question for the gurus out there: in ECMAScript, one
can create a new Array object with a length like so:

var animals = new Array(128);

This creates a new Array object with a "length" property set
to 128.
My question: Does this in any sense "preallocat e" memory for
any of these 128 slots?
The answer would be 'maybe, but probably not'. The important detail is
that even if the length property is pre-set to some value that action
should not result in the creation of any 'array index' properties of the
Array object, and without the creation of any 'array index' properties
there is no need for memory to be allocated to accommodate them.
Javascript arrays are supposed to be sparse. Whether some internal
details of the implementation of an Array could be optimised with some
internal pre-allocation of memory would depend on the implementation,
but the javascript programmer should not be able to tell whether that
was happening or not.
I've seen the word "preallocat e" bandied about, but
my experience with UAs tells me this term is being misused;
all 128 of those "slots" remain "undefined" , as do all
non-declared property names on any object.
For-in loops, or - hasOwnProperty - tests, would be more informative as
an object can have a property but that property can hold the undefined
value.
In writing my own code, I've stayed away from
declaring arrays using the above syntax, as I feel it's
somewhat misleading to indicate that an amount of memory
has been allocated that's in any way proportional to the
length given to the constructor. In fact, I can't really
think of much legitimate use for creating an Array object
with 128 "undefined" items, except to confuse C++ and Java
programmers. But, if it's actually allocating memory
here, maybe I'm wrong.
I would go along with Douglas Crockford here and just use empty Array
literals to create new Arrays, and forget about any notion of
pre-declaring the length.

Richard.

Sep 18 '07 #3
Richard Cornford wrote on 18 sep 2007 in comp.lang.javas cript:
I would go along with Douglas Crockford here and just use empty Array
literals to create new Arrays, and forget about any notion of
pre-declaring the length.
While post-declaring is usable:

<script type='text/javascript'>

var a = [];
a[17] = 'x';
a['notAnArrayMemb er'] = 'y'
alert(a.length) ; // 18
a.length = 3;
alert(a.length) ; // 3
alert(a[17]); // undefined
alert(a['notAnArrayMemb er']); // y

</script>

IE7 tested.

Would memory space garbage collection be a reason to do this?

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Sep 18 '07 #4
Richard Cornford wrote:
I would go along with Douglas Crockford here and just use empty Array
literals to create new Arrays, and forget about any notion of
pre-declaring the length.
JFTR: The (empty) Array literal notation is not universally supported.

The alternative that is supported since the Array feature was introduced,
is

new Array()

See http://PointedEars.de/scripts/es-matrix
PointedEars
--
"Use any version of Microsoft Frontpage to create your site. (This won't
prevent people from viewing your source, but no one will want to steal it.)"
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>
Sep 18 '07 #5
On Sep 17, 11:48 pm, "Richard Cornford" <Rich...@litote s.demon.co.uk>
wrote:
I would go along with Douglas Crockford here and just use empty Array
literals to create new Arrays, and forget about any notion of
pre-declaring the length.
That's what I've been doing, but looking through the code for
SpiderMonkey (Mozilla's JS engine) confirmed that this is indeed the
case (apologies for the C code on the JS list):

mozilla/js/src/jsarray.c: 2032:

static JSBool
Array(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval
*rval)
{
jsuint length;
jsval *vector;

/* If called without new, replace obj with a new Array object. */
if (!(cx->fp->flags & JSFRAME_CONSTRU CTING)) {
obj = js_NewObject(cx , &js_ArrayCla ss, NULL, NULL);
if (!obj)
return JS_FALSE;
*rval = OBJECT_TO_JSVAL (obj);
}

if (argc == 0) {
length = 0;
vector = NULL;
} else if (argc 1) {
length = (jsuint) argc;
vector = argv;
} else if (!JSVAL_IS_NUMB ER(argv[0])) {
length = 1;
vector = argv;
} else {

/******
We would get here using eg. new Array(128)
*/

if (!ValueIsLength (cx, argv[0], &length))
return JS_FALSE;
vector = NULL;
}
return InitArrayObject (cx, obj, length, vector);
}

/mozilla/js/src/jsarray.c: 779:

static JSBool
InitArrayObject (JSContext *cx, JSObject *obj, jsuint length, jsval
*vector)
{

/******
in the above example (new Array(128)), we would get here with params:
cx = <irrelevant context reference>, JSObject == <new Array
instance>, length == 128, vector == NULL
*/

jsval v;

JS_ASSERT(OBJ_G ET_CLASS(cx, obj) == &js_ArrayClass) ;
if (!IndexToValue( cx, length, &v))
return JS_FALSE;
STOBJ_SET_SLOT( obj, JSSLOT_ARRAY_LE NGTH, v);
/******
since "vector" is NULL, this test fails, returning TRUE;
InitArrayElemen ts never gets called
*/

return !vector || InitArrayElemen ts(cx, obj, 0, length, vector);
}

Sep 18 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
7667
by: ip4ram | last post by:
I used to work with C and have a set of libraries which allocate multi-dimensional arrays(2 and 3) with single malloc call. data_type **myarray = (data_type**)malloc(widht*height*sizeof(data_type)+ height* sizeof(data_type*)); //allocate individual addresses for row pointers. Now that I am moving to C++,am looking for something by which I can
1
2386
by: Roberto Dias | last post by:
I'm a newbie in C++ programming. I bought a book yet and I have learned by means internet donwloadble materials. I feel not confortable using multi-dimensional arrays. I simply cannot understand memory allocation principle. I have got some ideas that require this one, but only thoughts and no action I have done. Unfortunately, the Deitel book don't explore this topic well. Vectors? How to use them insted of multi-dimensional arrays? What...
9
3964
by: pvinodhkumar | last post by:
The number of elemets of the array, the array bound must be constant expression?Why is this restriction? Vinodh
20
2117
by: John Mark Howell | last post by:
I had a customer call about some C# code they had put together that was handling some large arrays. The performance was rather poor. The C# code runs in about 22 seconds and the equivalent C++.Net code runs in 0.3 seconds. Can someone help me understand why the C# code performance is so poor? I rewote the C# code to use a single dimenional array and the time went down to about 3 seconds, but that's still no explaination as to why the...
7
6442
by: heddy | last post by:
I have an array of objects. When I use Array.Resize<T>(ref Object,int Newsize); and the newsize is smaller then what the array was previously, are the resources allocated to the objects that are now thown out of the array released properly by the CLI?
4
5069
by: hobbes992 | last post by:
Howdy folks, I've been working on a c project, compiling using gcc, and I've reached a problem. The assignment requires creation of a two-level directory file system. No files have to be added or deleted, however it must be initialized by a function during run-time to contain so many users which each contain so many directories of which each contain so many files. I've completed the program and have it running flawlessly without implementing...
1
7973
by: Peterwkc | last post by:
Hello all expert, i have two program which make me desperate bu after i have noticed the forum, my future is become brightness back. By the way, my problem is like this i the first program was compiled and run without any erros but the second program has a run time error when the function return from allocate and the ptr become NULL. How to fixed this? Second Program: /* Best Method to allocate memory for 2D Array because it's ...
3
3336
by: aeo3 | last post by:
Hi All, Now, I am trying to build a project, I need to expand an array of pointer to classes. Moreover, this array includes some elements I want to delete them. So, I create another array, copy the elements which i want to keep and copy this array to the original one as follows This function to create two arrays it depends on the parameter x. void Econ::CreateFirms(int array,int x) { if(x==1) { FirmArray= new Firm*;
4
2470
by: somenath | last post by:
I have a question regarding the memory allocation of array. For example int array; Now according to my understanding 10 subsequent memory location will be allocated of size sizeof(int) *10 and this is done at compile time. Does it mean C compiler reserve some amount of memory for the array
0
8831
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9548
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9374
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9249
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8244
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3315
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.