Passing dynamic arrays

spir denis.spir at gmail.com
Tue Nov 9 14:38:01 PST 2010


On Tue, 09 Nov 2010 15:13:55 -0500
Pillsy <pillsbury at gmail.com> wrote:

> There's a difference between appending and appending in place. The problem with not appending in place (and arrays not having the possibility of a reserve that's larger than the actual amount, of course) is one of efficiency. Having
> 
> auto s = "foo";
> s ~= "bar";
> 
> result in a new array being allocated that is of length 6 and contains "foobar", and assigning that array to `s`, is obviously useful and desirable behavior. If the expansion can happen in place, that's a perfectly reasonable performance optimization to have in the case of strings or other immutable arrays. Indeed, one of the reasons that functional programming and GC go together like peanut butter and jelly is that together they let you get all sorts of wins in terms of efficiency from shared structure. 
> 
> However, I've found working with languages that mix a lot of imperative and functional constructs (Lisp is one, but not the only one) that if you're going to do this, it's really very important that there not be any doubt about when mutable state is shared and when it isn't. D is trying to be that same kind of multi-paradigm language.

+++

> This means that, for mutable arrays, having
> 
> int[] x = [1, 2, 3];
> x ~= [4, 5, 6];
> 
> maybe reallocate and maybe not seems like it's only really there to protect people from doing inefficient things by accident when they append onto the back of an array repeatedly (or to make that admittedly common case more convenient). This really doesn't strike me as worth the trouble. Like I said elsewhere, the uncertainty gives me the screaming willies. 

There is some trouble in there; but it's hard to point it clearly. After
	int[] ints1;
	...
	ints2 = ints1;
	...
depending of what happens to each array, especially when passed to funcs that could manipulate them, the relation initially established between variables may or may not be maintained. Also, it may be broken only in some cases, depending on what operations are performed during a given run.
Possibly, in practice, things are much easier to do right than seems at first sight. But my impression is I will be bitten more than once, and badly. (*)


Denis

(*) Reminds of python's famous gotcha which instead _establishes_ an unexpected relation:
	def f(i, l=[]):
	    l.append(i)
	    return l
	print f(1)	# [1]
	print f(1)	# [1, 1]
	print f(1)	# [1, 1, 1]
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d mailing list