7 ms·
just for the lolz, here is another way to do it without a buffer and using some java 8 features (lambdas) to avoid having to wrap the code in a try catch (techn
by benkillin 12y ago
just for the lolz, here is another way to do it without a buffer and using some java 8 features (lambdas) to avoid having to wrap the code in a try catch (technically you still are but it looks prettier IMHO):
public class SimpleJavaTest
{
public interface RunnableEx
{
// can't use Callable<Void> because that run method needs to return a value
public abstract void run() throws Exception;
}
public static void main(String[] args)
{
// write standard in to standard out:
uncheck( () -> {
int c;
while( (c = System.in.read()) > -1)
{
System.out.write(c);
}
} ).run();
}
public static Runnable uncheck(RunnableEx r)
{
return () -> {
try
{
r.run();
}
catch(Exception e)
{
throw new RuntimeException(e.getMessage(), e);
}
};
}
}
- beagle3 12y ago> it looks prettier IMHO ... And here's a fine example of Java culture. 2 lines do stuff, everything else is fluff, and it is considered prettier. BTW: I did not run this specific code, but dropping the buffer is likely to make this code take much, much more CPU (unless HotSpot is much better these days than it was in 2010 when I last used it). That's another pillar of Java culture - care not about performance. Disclaimer: I didn't test this, and any mention of performance requires testing, rather than reasoning. I don't have a Java compiler handy anymore, or I would test it.
- benkillin 12y agodropping the buffer makes it perform substantially slower - there are some benchmarks listed elsewhere on this thread
- jbooth 12y agoI'm a big believer in benchmarking before saying things, but I think we could skip the benchmarks when asking the question "does 1 4096-byte read or 4096 1-byte reads complete faster".
- beagle3 12y agoI would agree ... except that I've seen cases in which it didn't make a difference. e.g. if the File implementation had an internal buffer (C stdio's "FILE " does), and the read from that* buffer was inlined (from my past experience up to date as of early 2011, HotSpot doesn't, but LuaJIT does), it might not make any difference. Seriously, LuaJIT does things I've never thought I'd see a compiler (JIT or AOT) for any language (dynamic or statically typed) do. I used to reply to "sufficiently smart compiler" with "one hasn't appeared yet, despite at least 3 decades of waiting". But LuaJIT has appeared.