8

Reading the documentation of Pharo (Pharo By Example) the first difference is in the way that arrays are made.

A literal will follow this syntax

myArray := #(1 2 3)

while a dynamic array with

myArray := {1+2 . 4-2 . 3 }

A literal array will take values directly , containing numbers, strings and booleans. While a dynamic array will take full messages that will compile and insert their returning values to the array.

Is there are any other difference between the two ? Why do literal arrays exist if dynamic arrays can do what literal arrays do ?

Céline Aussourd
  • 10,214
  • 4
  • 32
  • 36
Kilon
  • 1,962
  • 3
  • 16
  • 23

2 Answers2

9

Dynamic array like { 1 + 2 . 4 - 2 . 3 } is basically a syntactic sugar for:

Array
  with: 1 + 2;
  with: 4 - 2;
  with: 3

Which makes sense because arrays are created quite often. Also you can incorporate this to create a dictionary for example:

{
  #keyOne   -> 5 .
  #keyTwo   -> 3 .
  #keyThree -> 1
} asDictionary

Literal arrays as actually literal and are defined before compile time.

Uko
  • 13,134
  • 6
  • 58
  • 106
  • thank you uko, can you please define "before compile time", I have seen this also in PBE but I am not sure I understand exactly what it means – Kilon May 15 '14 at 09:54
  • 1
    @Kilon when you "save a method" or officially: "accept changes" it is being compiled into a byte code. This is done for performance reasons, as it's faster for VM to interpret byte code commands, rather then AST itself or whatsoever. Now when you use: `2`, `@c`, `#sym`, `#(1 2 3)` and other literals, compiler knows that this things won't change and so can optimise the byte code. Whereas "dynamic array" is composed during a run time (when the byte code is executed by VM) and so you cannot do anything special about it – Uko May 15 '14 at 10:05
  • I see , so its about optimization and performance. Thanks its clear now. – Kilon May 15 '14 at 10:10
  • @Kilon yes. The thing is that dynamic array is not a literal. It's one more expression on the same level as assignment, message send and cascade. – Uko May 15 '14 at 10:19
5

Literal arrays are standard Smalltalk syntax, dynamic arrays are a Squeak (and therefore Pharo) extension. I believe similar syntax exists in other Smalltalks, but it's not universal.

So the reason literal arrays exist is because they always have - they're part of Smalltalk 80. Other than syntax and when they're evaluated, I don't think there's any other difference - I believe they both result in an object of the same type, it's only how they're initialized that's different.

Stuart Herring
  • 899
  • 6
  • 9