short parameters

public void foo(short bar)
{
}

foo(123); // compile error because the literal is converted to an int
foo((short)123); // works but icky
foo(123s); // I would like to do something like this…

Are there any tricks to get around having to manually typecast the literal using (short)?

I would like to save the 2 bytes but I would also like to avoid typing 7 extra characters each time.

First, if you do any lengthy calculations, make sure to use an int. If you use shorts, it will be slow because Java will convert all of them to ints. I couldn’t find a solution like you are wanting probably because Java wants you to type cast to warn people about what I just said. Having 2s might make people think that “short s = 2s + 4s + 5s” is just as fast as “short s = (short)(2 + 4 + 5)” when it’s not. Hopefully some one else will come along and give a better solution, but here are some solutions I can offer:


public void foo(int i) {
  short s = (short)i;
}


public void foo(short s) {
}

public void foo(int i) {
  foo((short)i);
}

Avoid embedding literals in your source? :persecutioncomplex:


final short someMeaningfulNameForTheLiteral = 123;
foo(someMeaningfulNameForTheLiteral);

You do realise that using a short instead of an int isn’t really going to save you anything, right?

unless you’re working with huge int arrays, which can be turned into short arrays.

but I doubt he’s running into a memory bandwidth bottleneck here

True, but the original code only shows a method parameter. It’s pretty rare to ever need a short instead of an int as a method param.

Indeed, a colleague (actually, my dad - nepotism ftw ;)) recently did some benchmarks of some intensive number-crunching in c# to see what difference various basic tweaks would make. It was basically synthesising a load of sin waves at audio rate via totally straightforward calls to Math.sin() IIRC. Doing processing with floats rather than doubles had a significant impact; significantly slower with floats! I can’t remember how big the difference was, and I wouldn’t rate the precision of the benchmark anyway, but it was enough to be quite clearly significant.

edit: it’s just occurred to me that if it was indeed calling Math.sin(), that’s fairly obviously the cause of the slowness given that it uses doubles, requiring lots of casts in the float case. Now I feel like I’ve brought shame on my whole family… shucks. I suppose the point that casts are costly, which was already made by Intuit, is the real point.

For the record, the test used lookup tables, not Math.sin(). Not sure why I suddenly thought otherwise.