473,226 Members | 1,336 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,226 software developers and data experts.

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 "preallocate" memory for any of
these 128 slots? I've seen the word "preallocate" 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 7983
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 "preallocate" memory for any of
these 128 slots? I've seen the word "preallocate" 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 "preallocate" 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 "preallocate" 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.javascript:
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['notAnArrayMember'] = 'y'
alert(a.length); // 18
a.length = 3;
alert(a.length); // 3
alert(a[17]); // undefined
alert(a['notAnArrayMember']); // 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...@litotes.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_CONSTRUCTING)) {
obj = js_NewObject(cx, &js_ArrayClass, 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_NUMBER(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_GET_CLASS(cx, obj) == &js_ArrayClass);
if (!IndexToValue(cx, length, &v))
return JS_FALSE;
STOBJ_SET_SLOT(obj, JSSLOT_ARRAY_LENGTH, v);
/******
since "vector" is NULL, this test fails, returning TRUE;
InitArrayElements never gets called
*/

return !vector || InitArrayElements(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
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 =...
1
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...
9
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
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...
7
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...
4
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...
1
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...
3
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...
4
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...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

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.