May 14, 2014 Re: Cost of assoc array? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Chris | Chris:
> foreach (size_t i; 0..myArray.length) {
> // do something with myArray[i];
> }
There are various better ways to use a foreach on an array:
foreach (immutable x; myArray) {
foreach (ref const x; myArray) {
foreach (ref x; myArray) {
Bye,
bearophile
|
May 14, 2014 Re: Cost of assoc array? | ||||
---|---|---|---|---|
| ||||
Posted in reply to bearophile | On Wednesday, 14 May 2014 at 13:49:22 UTC, bearophile wrote:
> Chris:
>
>> foreach (size_t i; 0..myArray.length) {
>> // do something with myArray[i];
>> }
>
> There are various better ways to use a foreach on an array:
>
> foreach (immutable x; myArray) {
>
> foreach (ref const x; myArray) {
>
> foreach (ref x; myArray) {
>
> Bye,
> bearophile
His code was for an associative array.
|
May 14, 2014 Re: Cost of assoc array? | ||||
---|---|---|---|---|
| ||||
Posted in reply to John Colvin | On Wednesday, 14 May 2014 at 13:44:40 UTC, John Colvin wrote: > > Yes, they are much faster. Normal array indexing is equivalent to *(myArray.ptr + index) plus an optional bounds check, whereas associative array indexing is a much, much larger job. > > Why were you using associative arrays in the first place? Unless your keys are somehow sparse* or of a non-integer type there isn't any reason to. It is very old code (dmd 2.052 times). When I set out to write it, I was a) new to the language and b) I could not yet tell whether or not I would need it (I think it also had to do with the way D was back then, but I don't remember my exact reasoning). It has always been in the back of my mind to change it into a normal array. It's basically a code corpse. > * How I see that constraint in that context: > > (maxKey - minKey) / nElements > 1 + epsilon > where epsilon is the maximum proportional wasted space you could afford in a normal array (emptyElements / usedElements). Bear in mind the memory overhead of associative arrays is itself non-zero. > > Also, while normal arrays tend to be more cache friendly than associative arrays, this isn't true for very sparse arrays. |
Copyright © 1999-2021 by the D Language Foundation