0

Not sure if this is a correct question for here but I was wondering about the Groovy keyword of def (and the equivalent of other dynamic or optionally typed languages).

One useful, or nice usage of something like this is that you could have one type of value assigned to a variable and then change it to another type.

For instance, let's say you get a map of two timestamps that represent a date range from your front end

def filters = [
                from: from,
                to  : to
        ]

Then when you do some validations you want to pass a date range in date objects to your DAO for SQL queries so you do something like the following

if(filters.from && filters.to) {
            def normalizedDateRange = DateUtil.buildDateRange(filters.from, filters.to, maxRangeDays)
            filters.from = normalizedDateRange.from
            filters.to = normalizedDateRange.to
        }

This is acceptable and you get away without needing to create a second map with very similar name or such. My question is if this causes too much overhead in languages like this and is this one of the reasons they are slower than JAVA let's say.

Some people say that you could consider the def as using Object in Java so it allocates enough space to store anything or maybe it store a reference and when you store something different it just frees the space it was taking and reallocates new space and just updates the reference?

Would I gain anything by creating a new object/map here and storing the new values there? Or is the gain so little that it's better to take advantage of the sugar syntax and "cheating" of Groovy?

Andreas Andreou
  • 818
  • 10
  • 31

2 Answers2

1

def will be lighter, since it is simply an empty reference, which might easily be garbage collected later on.

By storing variables in a map, you are storing a value in a specific structure which calculates hashcode and whatnot1 2. It will be heavier.

Of course a map has wonderful features and one shouldn't overlook this simply based on performance without checking if it is a true bottleneck. You could try writing a microbenchmark.

Community
  • 1
  • 1
Will
  • 14,348
  • 1
  • 42
  • 44
0

Remember, Groovy is optionally typed, not dynamically typed. So if you are writing a constant that holds a filter, you can do this to give the compiler and JVM hints on what to do:

static final Map filters = [ to: 'X', from: 'Y' ]

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
  • Yeah, sorry. However that it the point. The types exist. They are resolved in runtime. However, you can assign a new type to an existing variable. I would assume that what happens is that new memory is allocated according to the new type needed. That is why, in my example, the from and to in the start were long and then they became Date. My question is whether we should take advantage of this possibility in an optionally typed language or if it actually puts more overhead/load/whatever – Andreas Andreou Aug 05 '16 at 13:00